Overview

In Laravel, creating custom helper functions can be a convenient way to reuse logic or functionality across your application. Here’s a step-by-step guide on how to create and use custom helper functions in Laravel:


1. Create a Helpers File

Create a new file to hold your custom helper functions. A common practice is to create a file named helpers.php.

Location: Place this file in the app directory or within a subdirectory like app/Helpers.

For example:

app/Helpers/helpers.php

2. Add Your Helper Functions

Add your custom functions to the helpers.php file. For instance:

<?php

if (!function_exists('format_date')) {
    function format_date($date, $format = 'Y-m-d') {
        return \Carbon\Carbon::parse($date)->format($format);
    }
}

if (!function_exists('greet_user')) {
    function greet_user($name) {
        return "Hello, {$name}!";
    } 
}

Note: Wrapping each function with function_exists ensures you don’t get a “function already defined” error if the file is included multiple times.


3. Autoload the Helpers File

To make these functions available throughout your application, you need to autoload the file.

Option 1: Use Composer

  • Add the file to the autoload section of your composer.json file:

    "autoload": {
        "files": [
            "app/Helpers/helpers.php"
        ]
    }
    
  • Run the following command to update Composer’s autoload files:

    composer dump-autoload
    

Option 2: Include in the AppServiceProvider

If you prefer not to use Composer, you can include the helpers file in the AppServiceProvider or another service provider.

Edit the boot method in App\Providers\AppServiceProvider:

public function boot() {
    require_once app_path('Helpers/helpers.php');
}

4. Use Your Helper Functions

Now you can use the custom helper functions anywhere in your application, such as controllers, views, or routes.

For example:

$formattedDate = format_date('2025-01-28'); 
echo greet_user('John');

5. Optional: Write Tests for Your Helpers

It’s a good practice to test your helpers to ensure they work as expected. You can do this by writing unit tests.

Example test:

public function test_format_date_helper() {     
    $this->assertEquals('2025-01-28', format_date('2025-01-28')); 
}

By following these steps, you can create reusable custom helper functions in Laravel and integrate them seamlessly into your application.

6. Best practices

Here are some additional considerations and best practices when creating and using custom helper functions in Laravel:


1. Namespace (Optional)

While it’s not mandatory, you can define your helpers within a namespace if you want to organize them better or avoid potential conflicts with globally defined functions.

For example:

namespace App\Helpers;
use Carbon\Carbon;
if (!function_exists('App\Helpers\format_date')) {
    function format_date($date, $format = 'Y-m-d') {
        return Carbon::parse($date)->format($format);
    }
}

To use these functions, you’d need to import or reference them with their namespace:

use App\Helpers\format_date;
$formattedDate = format_date('2025-01-28');

2. Grouping Helpers

If you have many helpers, it might be beneficial to group them by purpose (e.g., string helpers, date helpers, etc.) in separate files. For example:

  • app/Helpers/StringHelpers.php
  • app/Helpers/DateHelpers.php

In the composer.json, add all helper files:

"autoload": {
    "files": [
            "app/Helpers/StringHelpers.php",
            "app/Helpers/DateHelpers.php"
        ]
}

Or require them in the AppServiceProvider:

require_once app_path('Helpers/StringHelpers.php');
require_once app_path('Helpers/DateHelpers.php');

3. Performance

Custom helpers loaded via Composer are included in the autoloader and loaded only when needed. However, if you include the helpers manually (e.g., in AppServiceProvider), they will always be loaded, which could slightly impact performance if the file is large. Use Composer’s autoload mechanism for better performance.


4. Documentation

Add comments or docblocks to your helper functions. This improves maintainability and helps other developers understand the purpose of each helper.

Example:

/** 
 * Format a date string to the specified format.
 * @param string $date
 * @param string $format
 * @return string  
 */ 
function format_date($date, $format = 'Y-m-d') {
    return \Carbon\Carbon::parse($date)->format($format); 
}

5. Avoid Overloading Global Functions

Ensure your helper function names are unique and don’t override existing PHP or Laravel global functions (e.g., array_merge, view, etc.). Use specific or descriptive names for your helpers.


6. Helpers vs. Service Classes

While helpers are quick and convenient, they might not be ideal for all use cases. For complex logic or operations requiring dependency injection, consider creating a Service Class instead.

For example, instead of:

function calculate_tax($amount, $rate) {
    return $amount * $rate;
}
namespace App\Services;
class TaxCalculator {
    public static function calculate($amount, $rate) {
        return $amount * $rate;
    } 
}

And call it:

use App\Services\TaxCalculator;  
$tax = TaxCalculator::calculate(100, 0.05);

7. Test Your Helpers

Since helpers are often globally available, ensure you have proper unit tests for them. You can organize tests for helpers in a dedicated test file like tests/Unit/HelpersTest.php.


8. Security

If your helpers process sensitive data (e.g., user inputs, passwords), ensure they follow best practices for validation, sanitization, and encryption.


9. Laravel Built-In Helpers

Before creating your own helper, check if Laravel already provides a similar helper. Laravel has many built-in helpers like str_slug, array_wrap, and collect. Use these whenever possible to avoid redundancy.


10. Middleware or Global Scope

If your helpers require a specific context (e.g., user authentication), make sure you invoke them in the right place, like in middleware or scoped within specific contexts.


By following these additional steps, you can create robust, well-organized, and performant helpers in your Laravel application!