Create Custom Helper Function in Laravel

We can see there are many helper functions in Laravel we are using like bcrypt(), str_slug() but sometimes we required some own customized function so we need to create a custom helper function for this.

So today we will learn how to create a helper function and how to configure this. with some steps below

Step 1. Create a helpers.php file

We are creating a helper.php file in the app folder for writing out custom helper function for this and a function dateFormat helper function for our project

use Carbon\Carbon;  

function dateFormat($date,$format)
  return Carbon::createFromFormat('Y-m-d', $date)->format($format);    

Step 2. Add helper file path in composer.json

Now we need to add the path of the helpers.php file to composer autoload section so it can be discovered automatically in our whole project

"autoload": {
  "psr-4": {
    "App\\": "app/",
    "Database\\Factories\\": "database/factories/",
    "Database\\Seeders\\": "database/seeders/"
  "files": [

Step 3. Autoload the Composer

Now run the below command to include the helpers.php file so we can use the file internal function everywhere in the project

composer dump-autoload

 Now we are done with the custom helper function in laravel, as of now we can use this function anywhere.

     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <title>Create Custom Helper Function in Laravel - The Tech Stuffs</title>
     <link rel="stylesheet" href="">
    <h3>Custom Helper Function in Laravel - The Tech Stuffs</h3>
    <h3>New Date Format: {{ dateFormat(date('Y-m-d'),'m/d/Y')  }}</h3>

Thankyou for following us and please drop a comment if its solved your problem and you learn something new. Thankyou and have a great day ahead.

TheTechStuffs Teams.

You May Also Like

About the Author: Sumanta Kabiraj

Leave a Reply

Your email address will not be published.