Creating Custom helpers in Laravel 5.4

Share:

In this post, I going to show you 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.

Below are step by step guide to create a custom helper in Laravel 5

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

No comments