How to create a custom helper in laravel 8

In this today’s article, we will learn about how we can create a custom helper in laravel 8.

Laravel provides many excellent helper functions that are convenient for doing things like working with arrays, file paths, strings, and routes, among other things like the beloved dd() function.

If you are new to Laravel or PHP, let’s walk through how you might go about creating your own helper functions that automatically get loaded by Laravel.

We are going to follow the below steps in order to create a custom helper function in Laravel.

  • Create A helper File
  • Add it in composer.json
  • Add Code in the helper file
  • Usage

Step :1 Create a helper file

Depending on your preference, you can organize the location of your helper file(s) however you want, however, here are a few suggested locations:

  • app/helpers.php
  • app/Http/helpers.php

I prefer to keep mine in app/Http/helpers.php.

Step:2 Add it in composer.json

Now I will add my helper path in composer.json file in autoload under ps4.To use your PHP helper functions, you need to load them into your program at runtime.

"files": [
helper path added in composer.json

After adding the code in the composer you must have to autoload the composer, to autoload composer run the below command.

composer dump-autoload

Step: 3 Add code in Helper File

Now we will add the code in the helper file, below code is created to change datetime format.


function formatDate($date){
    return date('d-M-Y g:i a', strtotime($date));

custom helper file

Step: 4 Usage

Now we will see how we can use our custom,helper function.

if you want to you it in your controller you can use in below way

$date = '2021-01-26 T 13:40';
formatDate($date); // call custom helper function

How to call helper function in blade file


Below image is example of the custom helper function

custom helper function example

Read Also: How to make trait in Laravel/

I hope you like the article on how to create custom helper in Laravel 8, please rate in 5 in order to boost my confidence.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Check Also
Back to top button