---
url: >-
  https://docs.corbitaltech.dev/products/whatsmark-saas/customization/custom-module/helper-functions.md
description: >-
  Utility helper functions for payment gateway module development in
  WhatsMarkSaaS
---

# Laravel Helper Functions - Complete Developer Reference

::: tip 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

::: code-group

```php [Basic Cache Operations] {2-5,8-11}
// Clear all application cache
clear_cache(); // [!code focus]

// Clear different cache types
clear_config(); // Configuration cache // [!code focus]
clear_route(); // Route cache // [!code focus]
clear_view(); // Compiled view cache // [!code focus]
```

```php [Advanced Cache Operations] {2-5}
// Tenant-specific cache management
clear_tenant_cache(tenant_id()); // [!code focus]
```

#### `clear_tenant_cache(int $tenant_id): void`

::: tip 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.

::: code-group

```php [Tenant Cache Usage] {5-10}
// 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()); // [!code focus]

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

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

:::

### File and Storage Functions

#### `create_storage_link(): void`

Creates the essential storage symlink for file access.

::: code-group

```php [Storage Link Usage] {3-8}
// In your module service provider or deployment script
try {
    create_storage_link(); // [!code focus]

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

:::

#### `checkRemoteFile(string $url): bool`

::: warning 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.

::: code-group

```php [Remote File Validation] {3-10}
// In webhook processing or file validation
$receiptUrl = 'https://payment-gateway.com/receipt/12345.pdf';

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

:::

### Text and String Functions

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

Smart text truncation with customizable limits and suffixes.

::: code-group

```php [Text Truncation Examples] {2-8}
// For payment descriptions
$description = truncate_text($longPaymentDescription, 100); // [!code focus]

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

// For email subject lines
$subject = truncate_text($emailSubject, 78, '...'); // [!code focus]
```

:::

### Invoice Functions

::: info 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.

::: code-group

```php [Invoice Formatting] {5-10}
// In invoice generation
$rawNumber = '001';
$invoiceNumber = formateInvoiceNumber($rawNumber); // Returns "INV-001"

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

:::

#### `format_draft_invoice_number(): string`

Returns the standardized draft invoice identifier.

::: code-group

```php [Draft Invoice Usage] {3-8}
// When creating draft invoices
$draftNumber = format_draft_invoice_number(); // Returns "INV-DRAFT"

// In conditional logic
if ($invoice->status === 'draft') { // [!code focus]
    $displayNumber = format_draft_invoice_number(); // [!code focus]
} else { // [!code focus]
    $displayNumber = formateInvoiceNumber($invoice->number); // [!code focus]
} // [!code focus]
```

:::

## Tenant Helper Functions

::: tip 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.

::: code-group

```php [Tenant Context Usage] {3-10}
// In payment gateway controllers
public function checkout($invoiceId)
{
    $tenant = current_tenant(); // [!code focus]

    if (!$tenant) { // [!code focus]
        abort(404, 'Tenant not found'); // [!code focus]
    } // [!code focus]

    $invoice = Invoice::where('tenant_id', $tenant->id) // [!code focus]
        ->where('id', $invoiceId) // [!code focus]
        ->firstOrFail(); // [!code focus]

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

:::

#### `tenant_id(): int|null`

Quick access to the current tenant's ID.

::: code-group

```php [Tenant ID Usage] {2-8}
// Simple tenant ID retrieval
$tenantId = tenant_id(); // [!code focus]

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

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

:::

#### `tenant_check(): bool`

Validates tenant context before proceeding with tenant-specific operations.

::: code-group

```php [Tenant Validation] {2-10}
// Security check in middleware or controllers
if (!tenant_check()) { // [!code focus]
    return redirect()->route('tenant.select') // [!code focus]
        ->with('error', 'Please select a valid tenant'); // [!code focus]
} // [!code focus]

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

    // Continue with payment processing...
}
```

:::

### Tenant Settings Functions

::: warning 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.

::: code-group

```php [Settings Retrieval] {2-12}
// Get payment gateway settings
$gatewayEnabled = tenant_setting('payment.tap_gateway_enabled', false); // [!code focus]
$apiKey = tenant_setting('payment.tap_gateway_api_key', ''); // [!code focus]

// Get UI preferences
$theme = tenant_setting('ui.theme', 'light'); // [!code focus]
$language = tenant_setting('ui.language', 'en'); // [!code focus]

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

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

:::

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

Saves individual tenant settings.

::: code-group

```php [Single Setting Save] {3-12}
// In payment gateway configuration
public function enableGateway()
{
    $setting = save_tenant_setting('payment', 'tap_gateway_enabled', true); // [!code focus]

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

:::

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

::: tip 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.

::: code-group

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

    // Save all settings at once
    $success = save_batch_tenant_setting('payment', $paymentSettings); // [!code focus]

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

:::

### Tenant URL Functions

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

::: info 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.

::: code-group

```php [Tenant Route Generation] {3-12}
// In payment gateway controllers
public function getCheckoutUrl($invoice)
{
    return tenant_route('payment.tap-gateway.checkout', [ // [!code focus]
        'invoice' => $invoice->id // [!code focus]
    ]); // [!code focus]
}

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

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

:::

## Payment Logger Functions

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

::: warning 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.

::: code-group

```php [Payment Logging Examples] {3-8,11-18,21-28}
// Basic payment logging
payment_log('Payment gateway initialized', 'info', [ // [!code focus]
    'gateway' => 'tap_gateway', // [!code focus]
    'tenant_id' => tenant_id(), // [!code focus]
    'sandbox_mode' => true // [!code focus]
]); // [!code focus]

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

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

:::

## 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"
  }
}
```
