Laravel Helpers
The Laravel framework provides many Helper Functions, conveniently these functions are global and can be used anywhere in the application. These can include managing arrays, objects, paths, strings and many more.
Creating Helper files in a Laravel app
You may want to re-use queries within the context of a Laravel application. By creating a Helper file, functions can be re-used anywhere within the applications instead of re-writing multiple lines of code over and over again. Depending on your preference, the location of your helper file(s) is subjective, however here is a suggested location:
- app/Helpers/{{name_of_helper_file}}.php
Autoloading
In order to use your PHP helper functions, you need to load them into your applications at runtime. In Laravel, you will see an autoload
key in the composer.json file. Composer has a files key (which is an array of file paths) that you can define inside of autoload:
"autoload": {
"files": [
"app/Helpers/exampleHelper.php"
],
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
Once you have added a new path to the files array, you need to dump the autoloader:
-
composer dump-autoload
Aliases
To call the class within a file its best to create an alias rather than writing the fully directory:
'aliases' => [
'exampleHelper' => App\Helpers\exampleHelper::class,
],
Because changes have been applied to the config/app.php
file run:
-
php artisan config:clear
Helper file example
<?php
namespace App\Helpers;
use App;
use Auth;
use DB;
use Request;
class exampleHelper {
public static function exampleFunction($variable)
{
// Do something
}
}
Helper file usage example
-
use exampleHelper;
-
exampleHelper::exampleFunction($variable);
Autoload
-
use exampleHelper;
-
exampleHelper::exampleFunction($variable);