Create Your Custom Helper Function in Laravel

tutspack laravel
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello Artisans,

In this laravel 8 custom helper functions tutorial, I will show you how you can create your own helper function in laravel 8. Sometimes we need a helper function in our Laravel project to do common tasks. For this kind of task if you create a custom helper function in Laravel then you can create it.

In this tutorial, I’ll show you step by step that the procedure of creating a custom helper function in your project. You know laravel also provides helper function for array, URL, route, path, etc. So now if you would like to add custom helper functions to your website or project directory then you have to follow just those steps and use them.

Step 1: Create helpers.php 

In this step, you need to create app/helpers.php in your laravel(inside the app folder) project and put the following code in that file:

app/helpers.php

if (!function_exists('changeDateFormate')) {
    function changeDateFormate($date,$date_format) : string
    {
         return \Carbon\Carbon::createFromFormat('Y-m-d', $date)->format($date_format);
    }
}

Step 2: Add File Path In composer.json 

Now in this step, you have to put path of helpers file,so basically open composer.json file and put following code in that file:

composer.json

"autoload": {

    "classmap": [

        ...

    ],

    "psr-4": {

        "App\\": "app/"

    },

    "files": [

        "app/helpers.php"

    ]

},

Step 3: Run this Command

this is the last step, you should just run following command:

composer dump-autoload

Now all are set to go. Now you can call it globally like this

{{ changeDateFormate(date('Y-m-d'),'m/d/Y')  }}

Hope you can understand.


Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Bangla Kings Software as Junior Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published. Required fields are marked *