How to create helper in laravel with example

How to create helper in laravel with example

In this tutorial i am going to ley you know that how can we create helper in laravel with example. Helper in any application works as a hook. We can use helper function anywhere in the whole application. 

In this example we will create two important methods as a helper function and will see the use of that helper function in the project. 

Many frameworks like codeigniter provide helper directory and structure to helper file and load that helper but laravel does not provide such type of helper directroy. 

But yet we are free to create helpers and load these helpers in the laravel application to use them anywhere throughout the application. So let’s strart to create custom helper in laravel with some example as mentioned above.

Step 1: Create helpers directory and file

Let’s start with creating a helpers directory under app directory. We can create only a file but if there are multiple helper files then it is a good prectice to put all helper files into a parent helpers directory.

Let’s create helper.php file and put some helper function like the file mentioned below.

app/helpers/helper.php

function getDaysBetweenTwoDates($date1, $date2)  
{ 
    // Calulating the difference in timestamps 
    $diff = strtotime($date2) - strtotime($date1); 
      
    // 1 day = 24 hours 
    // 24 * 60 * 60 = 86400 seconds 
    return abs(round($diff / 86400)); 
}


function getSubstringBetweenTwoString($str, $starting_word, $ending_word) 
{ 
    $subtring_start = strpos($str, $starting_word); 
    $subtring_start += strlen($starting_word);      
    $size = strpos($str, $ending_word, $subtring_start) - $subtring_start;     
    return substr($str, $subtring_start, $size);   
} 

Step 2: Register and Autoload Helper

We have created helper functions but it will not be available to use throughout the system. We will be needed to autoload helpers be composer autoload. So let’s add some code in composer file’s autoload section.

composer.json

"autoload": {
 
    "classmap": [
 
        ...
 
    ],
 
    "psr-4": {
 
        "App\\": "app/"
 
    },
 
    "files": [
 
        "app/helpers/helper.php"
 
    ]
 
},

After adding in aoutoload we will need to dump autoload by which autoloader could be reloaded. So we can do this by running the command below.

composer dump-autoload

Now these helper functions would be available everywhere in the project. We can use these helpers in views, controller, models where we needed.

Now we have successfully created custom helper in laravel. In the helpers file we can create class and its method instead of normal functions.