How to create custom helper function in laravel ?

Helper functions are the global functions that are accessible everywhere in the application. Laravel provides elegant way to define functions that are used frequently in a application. After defining a function as helper, we can access it any where inside the application. There are some such builtin functions. We can see those functions in laravel official documentation. 

When we need to perform some common operation like creating a slug from string frequently in multiple places inside laravel application, then it's better to create a helper function and call it whenever necessary.

At first we have to create a php file that contains such type of functions. Let's create a file inside app/Helper/ folder which is recommended normally.


Here, at first we checked getSlug function exists or not because we can't create a function that is already made available in laravel. The above function returns a slug of a string. Some example output of above function are,

if (!function_exists('getSlug')) {
    function getSlug($name)
        $slug = strtolower($name);
        $slug = str_replace(' ', '-', $slug);
        return $slug;

Input: Test String

Output: test-string

Input: Stack Learning

Output: stack-learning

Also Read: Display custom error message in Laravel

In order to use above function everywhere inside laravel application, we have to register the function to auto load in composer like this:

"autoload": {
        "classmap": [
        "psr-4": {
        "App\\": "app/"

After this we have to regenerate autoload files with following console command

composer dumpautoload

Now, we can use the getSlug function everywhere in our laravel application.

When we separate the common function, it will reduce the code duplication problem. These functions are like globle variables in php. We can define a function and then easily access the function anywhere in the application. Using such function provides a lot of advantages. When we want to change common functionality then one change in the helper function will change the functionality in every place where we have used the function. We can say such functions as reusable block of code easily accessible in the application.

share :

Sagar Gautam

A Computer Engineer from Nepal.

Leave your Feedback