DEV Community

Cover image for How to Create Your Own Helper Functions in Laravel
Ash Allen
Ash Allen

Posted on • Originally published at ashallendesign.co.uk

How to Create Your Own Helper Functions in Laravel

Introduction

Helper functions can be extremely useful in your Laravel projects. They can help to simplify your code in your projects in a clean and easy way. Laravel comes with many helper functions out-the-box such as dd(), abort() and session(). But as your projects start to grow, you'll likely find that you'll want to add your own.

In this article, we're going to look at how we can create and use our own custom PHP helper functions in our Laravel projects.

Creating the Helper Function

To add our own helper functions, we need to start by creating a new PHP file to place them in. So, let's create a helpers.php file inside our app folder. As a side note, this location is down to personal preference really. Another common place I've seen the file placed is inside an app/Helpers/helpers.php file. So, it's down to you to choose a directory that you feel works best for you.

Now, that we've got our file, we can add our helper function to it. As a basic example for this article, we're going to be creating a super-simple function that converts minutes to hours.

Let's add the function to our helpers.php file like so:

<?php

if (! function_exists('seconds_to_hours')) {
    function seconds_to_hours(int $seconds): float
    {
        return $seconds / 3600;
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see in the example above, the function itself is really simple. However, one thing that you might notice is that the function name is written in snake case (e.g. seconds_to_hours) rather than camel case (e.g. secondsToHours) like you'd usually see with method names on a class. You aren't necessarily fixed to using snake case for defining the function name, but you'll find that all of the Laravel helper functions are written this way. So, I'd probably advise to use the format just so that you can follow the typical standard and format that's expected. This is totally up to you though.

Another thing that you might have noticed is that we have wrapped the function name inside an 'if' statement. This is to stop us from accidentally redeclaring any helpers with the same name that have already been registered. For example, let's say that we were using a package that already had a seconds_to_hours() function registered, this would prevent us from registering our own function with the same name. To get around this, we could just simply change the name of our own function to avoid any clashes.

It's also really important to remember when creating helper functions that they are only supposed to be used as helpers. They aren't really meant to be used to perform any business logic, but rather to help you tidy up your code. Of course, you can add complex logic to them, but if this is something you're looking to do, I'd probably advise thinking about if the code would be a better fit in another place such as a service class, action class or trait.

Registering the Helper Function

Now that we've created our helper file, we need to register it so that we can use our new function. To do this, we can update our composer.json file so that our file is loaded at runtime on each request and is available for using. This is possible because Laravel includes the Composer class loader in the public/index.php file.

In your composer.json file, you should have a section that looks like this:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    }
},
Enter fullscreen mode Exit fullscreen mode

In this section, we just need to add the following lines to let Composer know that you want to load your file:

"files": [
    "app/helpers.php"
],
Enter fullscreen mode Exit fullscreen mode

The autoload section of your composer.json file should now look like this:

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

Now that we've manually updated the composer.json file, we'll need to run the following command to dump our autload file and create a new one:

composer dump-autoload
Enter fullscreen mode Exit fullscreen mode

Using the Helper Function

Congratulations! Your helper function should now be all set up and ready to use. To use it, you can simply use:

seconds_to_hours(331);
Enter fullscreen mode Exit fullscreen mode

Because it's been registered as a global function, this means you can use it in a variety of places such as your controllers, service classes and even other helper functions. The part that I love about helper functions most though is being able to use them in your Blade views. For example, let's imagine that we had a TimeServiceClass that contained a secondsToHours() method that did the same as our new function. If we were to use the service class in our Blade view, we might have to do something like this:

{{ \App\Services\TimeService::secondsToHours(331) }}
Enter fullscreen mode Exit fullscreen mode

As you can imagine, if this was used in multiple places across a page, it could probably start to make your view a bit messy.

Taking It Further

Now that we've seen how we can register and use the helpers, we will look at how we can take it one step further. Over time, as your Laravel projects grow, you might find that you have a large amount of helpers that are all in one file. As you can imagine, the file might start to look a bit unorganised. So, we might want to think about splitting our functions out into separate files.

For the sake of the article, let's imagine that we have many helpers in our app/helpers.php file; some related to money, some related to time and some related to user settings. We could start by splitting those functions out into separate files such as: app/Helpers/money.php, app/Helpers/time.php and app/Helpers/settings.php. This means that we can now delete our app/helpers.php file because we don't need it anymore.

After that, we can update our composer.json file in a similar way to before so that it nows loads our 3 new files:

"autoload": {
    "files": [
        "app/Helpers/money.php",
        "app/Helpers/settings.php",
        "app/Helpers/time.php",
    ],
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    }
},
Enter fullscreen mode Exit fullscreen mode

We'll need to remember to dump the Composer autoload file again by running the following command:

composer dump-autoload
Enter fullscreen mode Exit fullscreen mode

You should now be able to continue using your functions and have the benefit of them being split into logically-separated files.

Conclusion

Hopefully this article has shown you how to create and register your own PHP helper functions for your Laravel projects. Remember not to use them to perform complex business logic and to see them more as a way of tidying up little bits of code.

If you've enjoyed reading this post and found it useful, feel free to sign up for my newsletter so that you can get notified each time I publish a new article.

Keep on building awesome stuff! 🚀

Top comments (0)