Laravel Helpers

Ever needed to define your own Laravel global helper functions? It really simple in Laravel without having to write classes, facades or contracts.

Creating the helper file

Start by creating a new file in your app directory of your project. You can name your file anything you want. In this case it's named helpers.php.

After creating the file simply write your global helper functions. An example using teams is given below!

app/helpers.php
<?php
declare(strict_types = 1);

use App\Models\Team;

if (!function_exists('team')) {
    /**
     * Retrieve the current team.
     *
     * @returns \App\Models\Team|null
     */
    function team(): ?Team
    {
        return request()->user()->currentTeam;
    }
}

Registering the helper file

The helper file is now created and your functions defined, but they do not work right away! You'll need to update your composer.json file to make sure your helper file(s) are automatically autoloaded by Composer.

composer.json
{
    "autoload": {
        "files": ["app/helpers.php"]
    }
}

Run composer dump-autoload to make sure your helper file is automatically included!

michaelsnoeren.nl © 2021