Custom Helpers in Laravel

less than a minute of reading

Helper functions are simply custom PHP functions that you define in a certain place and then call from anywhere across a Laravel project. If you have to change anything, you do it in a single place – function’s definition. In this article I will show you, how I implemented custom helper function in Laravel.

Define Helper File

Starting from the root of your project, create a file called helpers.php under the app directory:

touch app/helpers.php

as a content use:

<?php

if (!function_exists('hello_world')) {
    function hello_world(): string
    {
        return 'Hello World';
    }
}
Register Helper File

Now open root composer.json and under autoload / psr-4, define files key with array containing relative path to your helper file.

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    },
    "files": [
        "app/helpers.php"
    ]
},

Finally dump autoloads so that Laravel is aware of the helper file:

composer dump-autoload
Usage

You can now call hello_world() function from anywhere like any other PHP method.

When it comes to defining new functions, you can import all available namespaces and use Laravel (facades or other helpers) or any other vendor package in your function's body.


Words: 196
Published in: Laravel · PHP
Last Revision: October 29, 2022

Related Articles   📚