How to create custom helper in Laravel?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Today now in this blog I would like to explain with you how to a create custom helper functions, in your laravel project . When we need some same functions and some repeating code, so at that time we need to create some helper functions that can help to easy way and every time we do not need to write more code and very flexible, on that way we can easily modify that code.

So now if we want to add a custom helper functions in our website or project directory then we need to follow just three step and then we can use it.

Step 1: Create helpers.php File

Now in this step, we need to create a app/Http/helpers.php in our laravel project and need put the following code in that file:

function changeDateFormate($date,$date_format){
	return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format($date_format);	
}
function productImagePath($image_name)
{
	return public_path('images/products/'.$image_name);
}
Step 2: Add File Path In composer.json File

So now in this step, we need to put path of helpers file,so it is basically open composer.json file and then put following code in that file:

"autoload": {
    "classmap": [

        ...

    ],

    "psr-4": {

        "App\\": "app/"

    },

    "files": [

        "app/Http/helpers.php" //Add This Line

    ]

},
Step 3: Run Command

At last in this is , we should just need to run following command:

composer dump-autoload

So ok, now at last we can use our custom helper functions as like changeDateFormate() and productImagePath(), So now i am going to give you an example of how to use custom helper functions:

Example

$imageName = 'example.png';$fullpath = productImagePath($imageName);print_r($fullpath);//AND{{ changeDateFormate(date('Y-m-d H:i:s'),'d-m-Y')  }}

Read Also : Select only one checkbox at a time using Jquery

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →