Laravel Custom Helper Functions (How-to)

In this post, we’re gonna be looking at how to create custom helper functions that can be globally used, meaning they can be called on both back-end such as Controllers and Services and front-end blade templates and other areas.

In just a few simple steps, we’ll implement a custom helper function whose purpose is to format an order number.

Example: 7643 to VRN000007643

For the purpose of this post, I’m using Laravel 8 with PHP 7.4.4.

Let’s get started!

Create helpers.php file

In your Laravel project, create a app/Support/helpers.php file and paste in the following code:

We’re using function_exists() to make sure that no other function with the same name already exists.

Otherwise, we might have some unpleasant surprises.

Autoload the file using composer.json

Now we have to tell Laravel that we have added a new file that must be accessible everywhere in the project.



Run composer dump-autoload command

In order for the changes to take effect, you have to run:

composer dump-autoload

This will start looking for all the classes and files it needs to include again, our helpers.php file being one of them.

In case your project has some hard-core caching in place, you can run the following commands to clear the application and configuration caches:

php artisan cache:clear

php artisan config:cache

Try out the function

In this example, we’re using a Controller to directly return the value of the function:

Now let’s call the same function inside a view:

And the output is what we expect it to be.

 

Laravel Custom Helper Function Output

Wrapping up

Creating a custom global helper function is fairly a straightforward process.

However, be careful not to let yourself be carried away by the illusions that Helpers are a convenient way of writing good quality code.

Because they often are not.

Most of the times Helper functions are used to store functionalities that you don’t know where else they belong.

And this is a sign of bad design.

Before you create a helper function like the one I showed above, ask yourself if this is the best approach for your application.

 

Let me know how would you make use of custom helper functions and what do you think about this article through comments below, or on Twitter at @pelu_carol.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.

 

You may also like...