Create a Custom Helper in Laravel

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

Create Custom Helper in Laravel

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

 

How to Create a Laravel Helper?

It is crucial for any web application to avoid code duplication. In laravel application custom helper functions can be defined and can be used throughout 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 application but a common and clean approach is to create it inside 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 set of tasks or purposes. To add custom helper functions to our helper file open app/Helpers/CustomHelper.php file and place 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 it manually. A custom laravel helper can be loaded by either AppServiceProvider or composer. Loading helper via AppServiceProvider is not recommended way so we will load our custom helper with composer.json like this:

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

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

composer dump-autoload

This helper function format_date() can now be used anywhere in 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 DRY (Don't Repeat Yourself) practice.