How to create custom helper functions in Laravel

Helper functions in Laravel make writing code more convenient. Laravel comes with quite a few already but I always find myself creating a few custom helper functions.

Creating helper functions in Laravel that you can use anywhere such as in blade files, controllers, etc is actually quite easy.

Custom Helper Functions in Laravel

  1. In your app directory create a file called helpers.php. In this file, you can write your helper functions. Here is an example of one.

    
     <?php
    
     use Carbon\Carbon;
    
     function tomorrow()
     {
         return Carbon::tomorrow();
     }
    
    
  2. Go to the composer.json file and find this area

    
     "autoload": {
             "psr-4": {
                 "App\\": "app/"
             },
             "classmap": [
                 "database/seeds",
                 "database/factories"
             ]
         }
    
    

    Add the helper file and it should look like this.

    
         "autoload": {
             "psr-4": {
                 "App\\": "app/"
             },
             "classmap": [
                 "database/seeds",
                 "database/factories"
             ],
             "files": [
                 "app/helpers.php" // This line was added
             ]
         },
    
    
  3. Now in the terminal run composer dump-autoload.

That's it! You should now be able to use your helper function throughout the application. For example, I can now go to any blade file and if I do {{tomorrow()}} it will work.

Want to learn how to code and make money online? Check out CodingPhase (referral link)