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.

General Helper Functions

Cache Management Functions

Application Cache Control

php
// Clear all application cache
clear_cache(); 

// 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_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 
]); 

Date Functions

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)

Language Functions

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

Usage Examples:

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
{
  "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.