Laravel Helpers
By Michael
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!
<?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;
}
}
Register 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.
{
"autoload": {
"files": ["app/helpers.php"]
}
}
Run composer dump-autoload to make sure your helper file is automatically included!