Laravel

Laravel: Creating Your Own Helpers

Assalamualaikum / Hi,

Helpers in Laravel, help you a lot in day-to-day coding with Laravel.

But, what if you want to create your helper? and of course, you want to organise it as well.

Usually I have my own helpers – see my helpers in Laravel Boilerplate.

But before doing that, you need to add the following snippet in your autoload key in composer.json file. You may refer here if you are not sure where to put.

...
"files": [
    "app/Support/helpers.php",
]
...

Then create the folder Support in app folder, then create an empty php file called helpers.php in app/Support directory. You should have something like this at the end.

Once you are done, you need to run composer dumpautoload -o, to make sure the helper get loaded into your Laravel application.

Now, the setup are done, and you may add any function that you think it’s globally required in your application, or probably you want to simplify how you deal with queries.

For instance, the role($name) to help me to get role based on name given, with adding cache mechanism as well. This helper improve speed of getting information, since i’m playing with cache to reduce the DB request.

You can see a lot more helpers I’ve created in my Laravel Boilerplate.

For organising your helpers, it is quite similar to my previous post – Laravel: Organising Your Route Files – using the code snippet.

Add the following code snippet to the end of your helper file you just created, then you can as many as you want the helper files in app/Support/. Keep it organise based on the concern.

collect(glob(__DIR__ . '/*.php'))
    ->each(function ($path) {
        if(basename($path) !== basename(__FILE__)) {
	    require $path;
        }
    });

Hope that will help you guys adding your own helpers. It may vary based on your requirement.

Thank your for reading. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

thirteen − 7 =