Home » Laravel » How to Create Helper in Laravel

How to Create Helper in Laravel

Helper in Laravel is a function that can be called globally without any context. You may already have used helpers for redirecting, returning responses, getting views or obtaining any entity from the global container.

But what to do if you want to create a custom helper? In this article, I will explain how to create helper in Laravel. I assume that you already have Laravel installed. If not, see this article.

How to Create Helper in Laravel

It is very simple. Just create a PHP file for your helpers. For example, app/helpers.php and place the wanted function into it. For example, let’s create helper with name upper():

vi app/helpers.php function upper(string $text) { return str_toupper($text); }

Then, open the composer.json file, find the autoload section and add the files section after the psr-4 section with your helpers file:

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

Next, update the Composer autoloading configuration:

composer dump-autoload

Now, you can use your helper in project code. For example, in the command or blade file. This helper will look like any other Laravel helper, but this approach is not about OOP. Pay attention: in the helpers.php file you should place only functions, not classes.

If you want to use a more OOP approach, just create Utils directory in the app directory. Then make class inside it with static methods. You can call them without creation object of the class. For example, create Str class with this content:

namespace Utils; class Str { public static function upper(string $text): string { return strtoupper($text); } }

When you want to call this helper, you should just import the class namespace and call static class method:

use Utils\Str; //... Str::upper($text);

In this case you don’t need to add any additional configuration into the composer.json, the class will be loaded using default PSR-4 autoloader.

Wrapping Up

In this article, we have explained how to create helper in Laravel. As you can see, it is very simple. What way do you prefer? Helper functions or classes with static methods? Why? Tell us, using the comment form below.

Your Reaction

Leave a Comment