Creating Helper File in Laravel


Creating a Helpers File



Problem

You have common functions you want available for every request.
But you don't want to dirty up app\start\global.php with a bunch of functions.

Solution

Create a helpers.php file.
First create the file app/helpers.php.
<?php
// My common functions
function test(){
 return 'hello';
}
?>
Then either load it at the bottom of app\start\global.php as follows.
// at the bottom of the file
require app_path().'/helpers.php';

Or change your composer.json file and dump the autoloader.
{
    "autoload": {
        "files": [
            "app/helpers.php"
        ]
    }
}
$ composer dump-auto

Call the function directly like:
$d = test();
It will be available everywhere.I can be also created in the package put the helper file in the src folder and change the path.

Comments