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.

  1. Creating Helper files
  2. Autoloading
  3. Aliases
  4. Helper file example
  5. Helper file usage example
  6. References

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:

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:

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:

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

Autoload

References