Defining Custom Laravel Helper Function

As mentioned in the official documentation of Laravel framework. Laravel includes a variety of global “helper” PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.

Example of helpers.
Example of helpers.

But sometimes we are forced to use custom helpers, which invite us to create our own helpers.

So let’s see in speedy way how we can create our own.

Create folder to contain our helpers.

You can choice any place in you app to create them, but to be more practice, we will create in under app/Utilities/Helpers.php

This name is more simple, readable and respect programming norms, you can see some norms tips in this post about code smells, but you can use instead of “Utilities” any name you want.

I will create a function that return some work if admin is logged in. So our Helpers.php should be something like that:

<?php 

    if(! function_exists('isAdmin')){ // check if the created function is already exist

        // check if is admin 
        function isAdmin(){
            // return fields from db 
            return $this->role === 'admin';
        }
        
    }

Above, I added a new function which I named isAdmin() that return checking role field on the table if equal to “Admin” role or not.

Autoloading the helpers

Simply go to your composer.json file. Find autoload and register your Helpers.php file.

Something like that:

    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        .
        .
        .
        "files": [
            "app/Utilities/Helpers.php"
        ]
    },

Update Autoload

Update the autoload is necessary when you change the autoload file. This command will do the work. So run

composer dump-autoload

Restart your app to check

To check if you’re doing everything with the correct way restart your app.

php artisan serve

Conclusion

After doing all of this defining and coding our helpers we have now isAdmin() function, and you can use it anywhere in your application.

HOPE ITS HELP.

Leave a Reply

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