Create a Custom Helper in Laravel

Laravel is a widely used, powerful PHP framework that comes with a rich set of built-in helpers and classes. Learn in this post how to create a helper in Laravel for reusability.

Create Custom Helper in Laravel

When developing a Laravel application, a custom Laravel helper is sometimes needed to reuse certain logic throughout the application. These helper functions can include unit conversion, formatting data, showing prices in a certain format, converting dates to a specific format or just simplifying repetitive tasks. In this post, we will see how to create a Laravel helper and load it into the application for use step by step.

 

How to Create a Laravel Helper?

It is crucial for any web application to avoid code duplication. In a Laravel application, custom helper functions can be defined and can be used throughout the application, making it easier for future changes. In order to use any helper function, we first need to create a helper file in Laravel. Helper files can be created anywhere in the application, but a common and clean approach is to create it inside the app/Helpers directory.

mkdir app/Helpers
touch app/Helpers/CustomHelper.php
 

Laravel Helper Custom Functions

After creating a CustomHelper.php file, we can now add any number of functions inside it. However, best practice is to create separate helpers for different sets of tasks or purposes. To add custom helper functions to our helper file, open the app/Helpers/CustomHelper.php file and place the following example code in it.

<?php

use Carbon\Carbon;

if (!function_exists('format_date')) {
/**
* Format a date into a human-readable format.
*
* @param Carbon|null $date The Carbon date or null.
* @param string $format The desired date format.
* @return string|null
*/
function format_date(?Carbon $date, string $format = 'd M Y'): ?string
{
if (!$date) {
return null;
}

return Carbon::parse($date)->format($format);
}
}
 

Load Custom Helper in Laravel

Laravel does not autoload the custom helper files, so we need to add them manually. A custom Laravel helper can be loaded by either AppServiceProvider or Composer. Loading helper via AppServiceProvider is not a recommended way, so we will load our custom helper with composer.json like this:

  • Open the composer.json file.
  • Find the autoload section in the file.
  • Place the custom helper under the files array.
"autoload": {
"files": [
"app/Helpers/CustomHelper.php"
]
}

After adding a helper in composer.json, it is important to regenerate composer's autoload files with the following command.

composer dump-autoload

This helper function format_date() can now be used anywhere in the application, including controllers, models and views etc. We demonstrated how to create a custom Laravel helper and how to load it. Creating and loading a Laravel helper is easy and helps to follow the DRY (Don't Repeat Yourself) practice.