How to Create Custom Helper Functions in Laravel – The Complete Guide

In this guide, you’ll learn how to create custom helper in Laravel, register them properly, and follow best practices to keep your codebase organized and efficient.

In Laravel development, helper functions are powerful tools that make your code cleaner and more reusable.

How to Create Custom Helper Functions in Laravel – The Complete Guide Image

Laravel 12 offers multiple ways to create helpers: 

1) Global Helper functions in app/Helpers/, 

2) Class-based Static Helper function, 

3) Service Provider registration for DI, 

4) View-specific in ViewHelpers, 

5) Macros in Traits. 

Best practice: Use class-based helpers with service providers for testability and organization.

efficient.


What are Helper Functions in Laravel?

Helper functions are simple PHP functions that can be used throughout your Laravel application. They often provide shortcuts or reusable logic that can be called anywhere—controllers, routes, views, or models.

Laravel provides many built-in Laravel helper functions (like asset(), route(), now(), etc.), but you can also define your own custom helper functions to extend Laravel’s functionality.


Why Use Custom Helper Functions?

Helper functions are reusable pieces of code that perform common tasks. Laravel comes with many built-in helpers like str_slug(), view(), and config(), but you'll often need to create your own.

Key benefits:

  • Code reuse: Write once, use everywhere
  • Consistency: Standardize common operations
  • Readability: Make complex operations simple to understand
  • Maintainability: Change logic in one place

Step-by-Step: How to Create Custom Helper Functions in Laravel

Method 1: Create a Helpers File

Location: app/Helpers/CustomHelpers.php

This is the simplest approach for basic helper functions available throughout your application.

  1. Now define your custom functions inside CustomHelpers.php

    <?php
    // app/Helpers/CustomHelpers.php
    
    if (!function_exists('format_price')) {
        function format_price(float $amount, string $currency = 'USD'): string
        {
            $symbol = match($currency) {
                'USD' => '$',
                'EUR' => '€',
                'GBP' => '£',
                default => $currency
            };
            
            return $symbol . number_format($amount, 2);
        }
    }
  2. Load the Helper File in composer.json

    "autoload": {
        "files": [
            "app/Helpers/CustomHelpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    }
  3. Run Composer Dump-Autoload

    composer dump-autoload

Usage

$formatted = format_price(99.99); // $99.99

You can use this helper in:

  • Blade templates

  • Controllers

  • API resources

  • Jobs, Events, etc.

Best for: Simple, app-wide utilities that don't need complex dependencies

Best Practices for Laravel Custom Helper Helpers

  • Use meaningful names for helper functions to avoid conflicts

  • Wrap each function in if (!function_exists()) to prevent redeclaration errors

  • Group related helpers in separate files (e.g., StringHelpers.php, ArrayHelpers.php)

  • Keep your helpers stateless and simple

Method 2: Class-Based Static Helpers

Location: app/Helpers/Utilities/StaticHelpers.php

Directly include static helper classes with the use keyword.

Implementation

  1. Define the class StaticHelpers.php:

    <?php
    
    namespace App\Helpers;
    
    class StaticHelpers
    {
        public static function slugify(string $text): string
        {
            return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $text)));
        }
    
        public static function truncate(string $text, int $length = 100): string
        {
            if (mb_strlen($text) <= $length) {
                return $text;
            }
            return mb_substr($text, 0, $length) . '...';
        }
    }

Usage Examples

In controllers:

use App\Helpers\StaticHelpers;
$slug = StaticHelpers::slugify($request->title);

In blade views:

@php
use App\Helpers\StaticHelpers;
@endphp
<div>{{ StaticHelpers::truncate($content, 200) }}</div>

Best for: Projects preferring explicit imports over global functions.

Method 3: Service Provider Registration

Location: app/Providers/HelperServiceProvider.php

For automatic loading and dependency injection.

Implementation

  1. Implement the helper:

    <?php
    // app/Helpers/Utilities/CurrencyHelper.php
    
    namespace App\Helpers\Utilities;
    
    use Illuminate\Http\Request;
    
    class CurrencyHelper
    {
        protected Request $request;
    
        public function __construct(Request $request)
        {
            $this->request = $request;
        }
    
        public function format(float $amount): string
        {
            $locale = $this->request->getPreferredLanguage() ?? 'en_US';
            $formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
            return $formatter->formatCurrency($amount, $this->request->get('currency', 'USD'));
        }
    }
  2. Generate the service provider:

    php artisan make:provider HelperServiceProvider
  3. Modify the provider:

    $this->app->singleton('currency.helper', function ($app) {
        return new \App\Helpers\Utilities\CurrencyHelper($app->make(Request::class));
    });
  4. Register in config/app.php:

    'providers' => [
        // ...
        App\Providers\HelperServiceProvider::class,
    ],

Usage Examples

In Controller:

$formattedPrice = app('string.helper')->format(99.99);
// Returns "$99.99" (EN) or "99,99 $" (FR) based on user's locale

In Blade formater:

@if(app('feature.helper')->isEnabled('new_checkout'))
    <!-- Show new checkout UI -->
@endif

Best for: Applications needing dependency injection or complex initialization

Method 4: View-Specific Helpers

Location: app/Helpers/ViewHelpers/

Helpers specifically for Blade templates.

Implementation

  1. Implement view helpers:

    <?php
    // app/Helpers/ViewHelpers/BladeDirectives.php
    
    namespace App\Helpers\ViewHelpers;
    
    use Illuminate\Support\Facades\Blade;
    
    class BladeDirectives
    {
        public static function register(): void
        {
            Blade::directive('money', function (string $expression) {
                return "<?php echo format_price($expression); ?>";
            });
    
            Blade::directive('readtime', function (string $expression) {
                return "<?php echo (int) ceil(str_word_count(strip_tags($expression)) / 200); ?>";
            });
        }
    }
  2. Register in AppServiceProvider:

    // app/Providers/AppServiceProvider.php
    
    public function boot(): void
    {
        \App\Helpers\ViewHelpers\BladeDirectives::register();
    }

Usage in Blade

@money($product->price)
@readtime($article->content) min read

Best for: View-specific formatting and presentation logic

Method 5: Macro Helpers

Location: app/Helpers/Traits/

Extend Laravel core classes with custom functionality.

Implementation

  1. Implement macros:

    <?php
    // app/Helpers/Traits/MacroableHelpers.php
    
    namespace App\Helpers\Traits;
    
    use Illuminate\Support\Collection;
    use Illuminate\Support\Str;
    
    trait MacroableHelpers
    {
        public static function registerMacros(): void
        {
            Collection::macro('toUpper', function () {
                return $this->map(fn($item) => Str::upper($item));
            });
    
            Str::macro('isEmail', function (string $value) {
                return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
            });
        }
    }
  2. Register in AppServiceProvider:

    // app/Providers/AppServiceProvider.php
    
    public function boot(): void
    {
        \App\Helpers\Traits\MacroableHelpers::registerMacros();
    }

Usage

$emails = collect(['test@example.com', 'invalid'])->filter(fn($e) => Str::isEmail($e));
$upper = collect(['a', 'b'])->toUpper(); // ['A', 'B']

Best for: Extending Laravel's core functionality

Performance Considerations

Laravel 12's optimizations make helper performance negligible:

  • Class-based helpers have minimal overhead
  • Opcache works perfectly with helper classes
  • Service providers are cached in production

Conclusion

Choose the right approach based on your project needs. For most Laravel 12 projects, I recommend starting with class-based static helpers in app/Helpers/ and adding other methods as needed. This provides a good balance of organization, testability, and performance.

Happy Coding! 😊

Do you Like?