How to Create Helpers in Laravel (Global Functions)

Helpers are one of the most used functions or structures when programming, they allow us to recycle functionalities, maintain the code and respect the principle of singularity of the SOLID pattern.

Below I will show you 2 ways I use helpers for my projects in Laravel.

Global Method or Function

This is the best known and most used form by all developers that, in addition to being easy to implement, allows you to use a functionality anywhere in your application without having to import or use anything external to the file in which it is going to be used.

Next, I will explain how to create a global function in Laravel and register it in the composer.json so that you can use it globally.

Create Global Function

Before creating our function, we are going to create a folder in the app directory of the root of your application, in our case we have called it Helpers and inside we have created a php file called methods, in which you must create all your methods or separate them and include them in that file.

Next, I will show you an example of how our helpers should look.

<?php if (!function_exists('my_method')) { function my_method() { // } }
Register Function if not Exists

As you can see, before each method there is a conditional that verifies that the function does not exist or has not been previously registered in our application, in this way we avoid conflicts and errors that could be generated within our code.

Register Helpers

Once you have your helpers file ready, we are going to register it in the composer.json using the path of our file inside the autoload attribute called files.

{ "autoload": { "files": [ "app/Helpers/methods.php" ] }, }
Register Methods File in composer.json

Once you've registered your helpers, you'll need to refresh the composer autoload so that Laravel can make use of these methods globally.

composer dumpautoload
Command to Refresh Composer Autoload

Suggestions

Although this way of creating global functions is the most used, personally, I have made a slight modification to make it easier and more useful to create the same function, avoiding having to write the conditional and allowing access to them more quickly and easily.

This modification that I am talking about is simply using a prefix that has not been used in the application, as I show below.

<?php function x_method() { // }
Create Function with a Prefix

In this case, the prefix that I have used is "x_" so that when you want to use a function that you have registered, you will simply write the prefix "x_" and the idle, in my case Visual Studio Code, it will show you all the global functions that start with that prefix, allowing you to quickly access the list of functions that you have written and above all, without interfering with the methods of the framework itself.