How to Create Custom helpers in Laravel

two dates Laravel 5 MAKE Create Custom helpers

I am going to share How to Create Custom helpers in Laravel. Laravel Helpers are PHP functions that written to perform specific programming task. Laravel comes with many inbuilt helper functions.Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.

Also Read: How to Clear cache in shared hosting server in laravel

Here is Step for Create Custom helpers in Laravel

Step1: In App/Http folder create a new file helpers.php and put below code in that file.

//Php function to  extension of upload file.
function getFileExtension($file_name){
      $temp= explode(".", $file_name);
      return $temp[count($temp)-1];
}

Step 2: In order to call helper function we need to add helper file path in autoload array of composer.json of project.To add your helper autoload , please open composer.json of root Laravel folder and add below codes.

"autoload": {

    "classmap": [
        ...
    ],

    "psr-4": {
        "App\\": "app/"
    },

    "files": [
        "app/Http/helpers.php" //Add This Line

    ]

},

Step 3: Running composer dump-autoload command to autoload files in framework.

composer dump-autoload

Your helper is created now and ready to use. You can call your helper function as PHP normal functions.

$file_name = 'example.png';

$extension=getFileExtension($file_name);

echo $extension; // outputs png

Leave a Reply