Skip to content

Laravel Helper Functions - Complete Developer Reference

Your Development Toolkit

This comprehensive guide covers all the helper functions available in our Laravel TALL stack application. These functions are your everyday tools for cache management, tenant operations, WhatsApp integration, email handling, and much more.

These aren't just random utility functions - they're carefully crafted tools that handle the complex multi-tenant architecture, caching strategies, and business logic that would otherwise require dozens of lines of code.

Think of this as your developer's Swiss Army knife. Each function is designed to solve specific problems you'll encounter daily when building payment gateways and other modules.

Helper Function Philosophy

Our helper functions follow three core principles:

  • Tenant-Aware: Automatically handle multi-tenant context
  • Performance-Optimized: Use caching and efficient database queries
  • Error-Safe: Return sensible defaults rather than throwing exceptions

General Helper Functions

Cache Management Functions

WARNING

Cache Management is Critical

In a multi-tenant application, proper cache management can make the difference between a fast, responsive system and one that crawls under load. These functions are essential for maintaining performance.

Application Cache Control

php
// Clear all application cache
clear_cache(); 

// Clear tenant-specific cache
clear_cache(123); 

// Clear different cache types
clear_config(); // Configuration cache
clear_route(); // Route cache
clear_view(); // Compiled view cache
php
// Tenant-specific cache management
clear_tenant_cache(tenant_id()); 

clear_cache(?int $tenant_id = null): void

Clears the application cache with optional tenant-specific clearing.

Function Details

Parameters:

  • $tenant_id (int|null) - Optional tenant ID for tenant-specific clearing

Returns: void

Usage Examples:

php
// Clear global cache
clear_cache();

// Clear cache for specific tenant
clear_cache(123);

// Use with current tenant
clear_cache(tenant_id());

When to Use:

  • After updating payment gateway settings
  • When deploying new module configurations
  • After bulk data changes that affect caching

clear_tenant_cache(int $tenant_id): void

Tenant Cache Strategy

This function clears all tenant-specific cached data including translations, settings, and computed values. Use this after making changes that affect a specific tenant.

Clears comprehensive tenant-specific cache including translations and settings.

php
// In your payment gateway settings controller
public function update(Request $request)
{
    // Save settings...

    // Clear tenant cache to ensure changes take effect immediately
    clear_tenant_cache(tenant_id()); 

    payment_log('Cache cleared after settings update', 'info', [ 
        'tenant_id' => tenant_id() 
    ]); 

    return redirect()->back()->with('success', 'Settings updated!');
}

File and Storage Functions

Creates the essential storage symlink for file access.

php
// In your module service provider or deployment script
try {
    create_storage_link(); 

    payment_log('Storage link created successfully', 'info'); 
} catch (Exception $e) { 
    payment_log('Failed to create storage link', 'error', [], $e); 
} 

checkRemoteFile(string $url): bool

Remote File Validation

Always validate remote files before processing, especially when dealing with user-uploaded content or webhook payloads.

Validates remote file accessibility via HTTP.

php
// In webhook processing or file validation
$receiptUrl = 'https://payment-gateway.com/receipt/12345.pdf';

if (checkRemoteFile($receiptUrl)) { 
    // File is accessible, proceed with download/processing
    $fileContent = file_get_contents($receiptUrl); 
    // Process file...
} else { 
    payment_log('Receipt file not accessible', 'warning', [ 
        'url' => $receiptUrl 
    ]); 
}

Text and String Functions

truncate_text(string $text, int $limit = 50, string $suffix = '......'): string

Smart text truncation with customizable limits and suffixes.

php
// For payment descriptions
$description = truncate_text($longPaymentDescription, 100); 

// For transaction notes in admin tables
$note = truncate_text($transaction->notes, 50, '...'); 

// For email subject lines
$subject = truncate_text($emailSubject, 78, '...'); 

Invoice Functions

Invoice Number Formatting

Our application uses standardized invoice numbering. These functions ensure consistency across all tenants and modules.

formateInvoiceNumber(string $invoice_number): string

Formats invoice numbers with the standard "INV-" prefix.

php
// In invoice generation
$rawNumber = '001';
$invoiceNumber = formateInvoiceNumber($rawNumber); // Returns "INV-001"

// In payment gateway integration
$paymentData = [ 
    'invoice_id' => formateInvoiceNumber($invoice->number), 
    'amount' => $invoice->total, 
    'description' => "Payment for {$invoiceNumber}"
]; 

format_draft_invoice_number(): string

Returns the standardized draft invoice identifier.

php
// When creating draft invoices
$draftNumber = format_draft_invoice_number(); // Returns "INV-DRAFT"

// In conditional logic
if ($invoice->status === 'draft') { 
    $displayNumber = format_draft_invoice_number(); 
} else { 
    $displayNumber = formateInvoiceNumber($invoice->number); 
} 

Tenant Helper Functions

Tenant Context is Everything

In our multi-tenant architecture, these functions are your gateway to understanding and manipulating tenant-specific data. They handle all the complex tenant resolution logic automatically.

Core Tenant Functions

current_tenant(): Tenant|null

Gets the current active tenant with intelligent caching and subdomain resolution.

php
// In payment gateway controllers
public function checkout($invoiceId)
{
    $tenant = current_tenant(); 

    if (!$tenant) { 
        abort(404, 'Tenant not found'); 
    } 

    $invoice = Invoice::where('tenant_id', $tenant->id) 
        ->where('id', $invoiceId) 
        ->firstOrFail(); 

    return view('payment.checkout', compact('invoice', 'tenant'));
}

tenant_id(): int|null

Quick access to the current tenant's ID.

php
// Simple tenant ID retrieval
$tenantId = tenant_id(); 

// In database queries
$transactions = Transaction::where('tenant_id', tenant_id()) 
    ->where('gateway', 'tap_gateway') 
    ->get(); 

// In logging
payment_log('Payment processed', 'info', ['tenant_id' => tenant_id()]); 

tenant_check(): bool

Validates tenant context before proceeding with tenant-specific operations.

php
// Security check in middleware or controllers
if (!tenant_check()) { 
    return redirect()->route('tenant.select') 
        ->with('error', 'Please select a valid tenant'); 
} 

// In service classes
public function processPayment($data)
{
    if (!tenant_check()) { 
        throw new InvalidTenantException('No active tenant context'); 
    } 

    // Continue with payment processing...
}

Tenant Settings Functions

Settings Performance

Tenant settings are heavily cached. Always use clear_tenant_cache() after batch updates to ensure consistency.

tenant_setting(string $key, mixed $default = null): mixed

Retrieves tenant-specific settings using dot notation.

php
// Get payment gateway settings
$gatewayEnabled = tenant_setting('payment.tap_gateway_enabled', false); 
$apiKey = tenant_setting('payment.tap_gateway_api_key', ''); 

// Get UI preferences
$theme = tenant_setting('ui.theme', 'light'); 
$language = tenant_setting('ui.language', 'en'); 

// Get notification settings
$emailEnabled = tenant_setting('notifications.email_enabled', true); 
$smsEnabled = tenant_setting('notifications.sms_enabled', false); 

// Complex nested settings
$paymentConfig = tenant_setting('payment.gateways.tap.configuration', []); 

save_tenant_setting(string $group, string $key, mixed $value): TenantSetting|null

Saves individual tenant settings.

php
// In payment gateway configuration
public function enableGateway()
{
    $setting = save_tenant_setting('payment', 'tap_gateway_enabled', true); 

    if ($setting) { 
        payment_log('Payment gateway enabled', 'info', [ 
            'gateway' => 'tap_gateway', 
            'tenant_id' => tenant_id() 
        ]); 
    } 
}

save_batch_tenant_setting(string $group, array $settings): bool

Batch Updates for Performance

When updating multiple related settings, always use the batch function. It's much more efficient and maintains data consistency.

Efficiently saves multiple tenant settings in one operation.

php
// In payment gateway setup
public function configureGateway(Request $request)
{
    // Prepare settings array
    $paymentSettings = [ 
        'tap_gateway_enabled' => $request->boolean('enabled'), 
        'tap_gateway_api_key' => $request->input('api_key'), 
        'tap_gateway_secret_key' => $request->input('secret_key'), 
        'tap_gateway_sandbox_mode' => $request->boolean('sandbox_mode'), 
        'tap_gateway_currency' => $request->input('currency', 'USD') 
    ]; 

    // Save all settings at once
    $success = save_batch_tenant_setting('payment', $paymentSettings); 

    if ($success) { 
        clear_tenant_cache(tenant_id()); // Clear cache for immediate effect
        return redirect()->back()->with('success', 'Settings saved successfully!');
    }
}

Tenant URL Functions

tenant_route(string $name, array $parameters = [], bool $absolute = true): string

Multi-Tenant Routing

Our routing system automatically handles tenant context. These functions ensure URLs are generated correctly for the current tenant's subdomain.

Generates tenant-aware route URLs with proper subdomain handling.

php
// In payment gateway controllers
public function getCheckoutUrl($invoice)
{
    return tenant_route('payment.tap-gateway.checkout', [ 
        'invoice' => $invoice->id 
    ]); 
}

// In email templates or notifications
$paymentUrl = tenant_route('billing.invoices.show', ['invoice' => $invoice->id]); 
$settingsUrl = tenant_route('settings.payment-gateways'); 

// In webhook callbacks
$callbackUrl = tenant_route('webhooks.tap-gateway.handle', [], true); 

Payment Logger Functions

payment_log(string $message, string $level = 'info', array $context = [], ?Throwable $exception = null, $tenantId = null): void

Logging Security

Never log sensitive data like API keys, passwords, or full credit card numbers. Always sanitize context data before logging.

Write payment logs with consistent formatting and tenant isolation.

php
// Basic payment logging
payment_log('Payment gateway initialized', 'info', [ 
    'gateway' => 'tap_gateway', 
    'tenant_id' => tenant_id(), 
    'sandbox_mode' => true
]); 

// Error logging with exception
try {
    $result = $paymentGateway->processPayment($data);
} catch (PaymentException $e) {
    payment_log('Payment processing failed', 'error', [ 
        'gateway' => 'tap_gateway', 
        'invoice_id' => $invoice->id, 
        'amount' => $invoice->total, 
        'error_code' => $e->getCode() 
    ], $e); 
}

// Success logging with details
payment_log('Payment completed successfully', 'info', [ 
    'gateway' => 'tap_gateway', 
    'transaction_id' => $result->transactionId, 
    'amount' => $invoice->total, 
    'currency' => $invoice->currency, 
    'processing_time' => microtime(true) - $startTime 
]); 

Feature Helper Functions

feature(string $featureSlug): bool

Feature Flag System

Our application uses feature flags to control access to functionality based on tenant subscriptions or system-wide toggles. Always check features before displaying UI or processing requests.

Checks tenant access to specific features based on their subscription or configuration.

php
// In payment gateway controller
public function index()
{
    if (!feature('payment_gateways')) { 
        abort(403, 'Payment gateways not available for your plan'); 
    } 

    return view('payment.gateways.index'); 
}

// In Blade templates
@if(feature('advanced_reporting'))
    <a href="{{ tenant_route('reports.advanced') }}" class="btn btn-primary">
        {{ t('advanced_reports') }} 
    </a>
@endif

Practical Usage Examples

Payment Gateway Integration

php
class TapGatewayController extends Controller
{
    public function processPayment(Request $request, $invoiceId)
    {
        // Validate tenant context
        if (!tenant_check()) { 
            return redirect()->route('tenant.select'); 
        } 

        // Get tenant-specific settings
        $apiKey = tenant_setting('payment.tap_gateway_api_key'); 
        $sandboxMode = tenant_setting('payment.tap_gateway_sandbox_mode', true); 

        if (empty($apiKey)) { 
            return redirect()->back()->with('error', t('payment_gateway_not_configured')); 
        } 

        try {
            // Log payment attempt
            payment_log('Payment processing started', 'info', [ 
                'gateway' => 'tap_gateway', 
                'invoice_id' => $invoiceId, 
                'tenant_id' => tenant_id(), 
                'amount' => $request->input('amount') 
            ]); 

            // Process payment...
            $result = $this->paymentService->process($request->all());

            if ($result->success) {
                // Log success
                payment_log('Payment completed', 'info', [ 
                    'transaction_id' => $result->transactionId, 
                    'gateway' => 'tap_gateway'
                ]); 

                // Generate success URL
                $successUrl = tenant_route('invoices.show', ['invoice' => $invoiceId]); 
                return redirect($successUrl)->with('success', t('payment_successful')); 
            }

        } catch (Exception $e) {
            payment_log('Payment failed', 'error', [
                'invoice_id' => $invoiceId,
                'error' => $e->getMessage()
            ], $e);
        }
    }
}

Settings Management

php
class PaymentSettingsController extends Controller
{
    public function update(Request $request)
    {
        // Validate feature access
        if (!feature('payment_gateway_management')) { 
            abort(403); 
        } 

        // Prepare settings for batch update
        $settings = [ 
            'tap_gateway_enabled' => $request->boolean('enabled'), 
            'tap_gateway_api_key' => $request->input('api_key'), 
            'tap_gateway_webhook_secret' => $request->input('webhook_secret') 
        ]; 

        // Save settings
        if (save_batch_tenant_setting('payment', $settings)) { 
            // Clear tenant cache for immediate effect
            clear_tenant_cache(tenant_id()); 

            payment_log('Payment settings updated', 'info', [ 
                'changes' => array_keys($settings) 
            ]); 
        }

        // Redirect with success message
        return redirect(tenant_route('settings.payment-gateways')) 
            ->with('success', t('settings_updated_successfully')); 
    }
}

format_date_time($dateTime): string

Purpose: Formats date and time according to tenant-specific or system-wide preferences including timezone, date format, and time format.

Parameters:

  • $dateTime (string|Carbon|DateTime) - The date/time value to format

Returns: string - Formatted date and time string

Implementation Details:

  • Automatically detects tenant context using tenant_check()
  • Retrieves timezone, date format, and time format from tenant/system settings
  • Supports both 12-hour and 24-hour time formats
  • Uses Carbon for reliable date/time manipulation
  • Falls back to application defaults if settings are unavailable

Multi-Tenant Behavior:

php
// In tenant context
if (tenant_check()) {
    $tenantSettings = tenant_settings_by_group('system');
    $timezone = $tenantSettings['timezone'] ?? config('app.timezone');
    $dateFormat = $tenantSettings['date_format'] ?? config('app.date_format');
    $timeFormat = $tenantSettings['time_format'] == '12' ? 'h:i A' : 'H:i';
} else {
    // Admin/system context
    $systemSettings = get_batch_settings([
        'system.timezone',
        'system.date_format',
        'system.time_format',
    ]);
    // ... process system settings
}

Usage Examples:

php
// Basic usage
$formatted = format_date_time('2024-01-15 14:30:00');
// Output: "Jan 15, 2024 2:30 PM" (tenant-specific format)

// With Carbon instance
$formatted = format_date_time(now());

// With database timestamp
$user = User::find(1);
$formatted = format_date_time($user->created_at);

Supported Date Formats:

  • Y-m-d - 2024-01-15
  • m/d/Y - 01/15/2024
  • d/m/Y - 15/01/2024
  • M d, Y - Jan 15, 2024
  • F d, Y - January 15, 2024

Supported Time Formats:

  • 12-hour: h:i A (2:30 PM)
  • 24-hour: H:i (14:30)

t($key, $replace = [], $locale = null): string

Purpose: Tenant-aware translation function with caching and fallback support.

Parameters:

  • $key (string) - Translation key (dot notation supported)
  • $replace (array) - Key-value pairs for placeholder replacement
  • $locale (string|null) - Specific locale override

Returns: string - Translated text or original key if not found

Implementation Details:

  • Uses LanguageService for consistent language resolution
  • Implements 1-hour caching per tenant and language combination
  • Automatically falls back to default English files
  • Supports tenant-specific cache keys for isolation
  • Handles missing translation files gracefully

Caching Strategy:

php

php
if (tenant_check()) {
    $tenant = current_tenant();
    $locale = $tenant->id.'_tenant_'.$locale;
}

$translations = Cache::remember("translations.{$locale}", 3600, function () use ($data) {
    if (file_exists($data['filePath'])) {
        return json_decode(file_get_contents($data['filePath']), true) ?? [];
    }
    return [];
});

Usage Examples:

php

php
// Basic translation
echo t('welcome.message'); // "Welcome to our platform"

// With placeholders
echo t('user.greeting', ['name' => 'John']); // "Hello, John!"

// With specific locale
echo t('button.submit', [], 'es'); // "Enviar"

// Nested keys
echo t('dashboard.stats.total_users'); // "Total Users"

// Fallback behavior
echo t('non.existent.key'); // Returns "non.existent.key"

// In Blade templates
{{ t('page.title') }}

// With Laravel's old input
<input placeholder="{{ t('form.email.placeholder') }}" value="{{ old('email') }}">

Translation File Format:

json

json
{
    "welcome": {
        "message": "Welcome to our platform",
        "subtitle": "Get started with your journey"
    },
    "user": {
        "greeting": "Hello, :name!"
    },
    "button": {
        "submit": "Submit",
        "cancel": "Cancel"
    }
}

© 2024 - Corbital Technologies. All rights reserved.