How to Create a Laravel Helper

To begin with, I would rather let the Laravel official site speak about helpers.

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.

So, basically, helpers in Laravel are built-in utility functions that you can call from anywhere within your application. If they hadn't been provided by the core framework, you might have ended up developing your own helper classes.

Although the core provides a variety of helpers already, there’s always a chance that you’ll need your own and would like to develop one so you don’t have to repeat the same code here and there, thus enforcing better maintainability. You'll learn how to create a custom Laravel helper in this tutorial.

Helpers in Laravel

As we discussed earlier, there are plenty of helpers available in the core of the Laravel framework. They are grouped together based on the functionality they provide. Here’s a list of helper groups.

Arrays

Helpers in this group provide functionality to manipulate array elements. More often than not, you're in the situation where you want to perform different operations on array elements. So this is the place where you should look first to see if what you're looking for already exists.

Paths

I find helpers in this category most useful. They return the fully qualified path of different directories like app, storage, config, and the like. I bet you're using most of these helpers already in your Laravel application.

Strings

String manipulation is something inevitable in your day-to-day application development. Although there are plenty of string manipulation functions provided by PHP itself, you'll find a few more useful goodies in this section.

URLs

You'll find very few in this category, but they are used throughout the application. They are used to generate route, asset, and form action URLs.

Miscellaneous

This category contains helpers that provide a variety of functionalities ranging from logging to debugging and many more.

For a complete reference of Laravel helpers, there's no better place than the official documentation.

Create Your First Custom Helper

Now you have a basic understanding of Laravel helpers and what they are used for. In this section, I’ll go ahead and demonstrate how you can create your own custom helper that can be used globally in your Laravel application.

To keep things simple and easy to understand, it’ll be a pretty basic helper that takes a userid and returns a username as a response. Of course, that doesn’t sound fancy, but I believe it’s enough to demonstrate the concept, and you could always extend it to fulfill your complex requirements.

I assume that you have a users table in your database and it has at least two fields—userid and username.

The Skeleton of a Laravel Helper

Before we move ahead and actually create the files, let’s have a quick look at the files that we’re going to create in the rest of the article.

  • app/Helpers/Envato/User.php: It’s our helper file that holds the logic of our helper.
  • app/Providers/EnvatoServiceProvider.php: It’s a custom service provider file that loads our custom helper file.
  • config/app.php: In this file, we’ll declare our custom service provider, and it also helps us to define an alias to our helper so that we don’t have to use the fully qualified class name of our helper.
  • routes/web.php: A pretty standard Laravel route file where we’ll actually test our helper.

Create Helper Files

Although you could place your helper files anywhere in your application, the more intuitive and standard way suggests that it should go under your app directory.

So go ahead and create a Helpers/Envato directory under app and create a User.php file with the following contents. Of course, you could place it directly under the app or app/Helpers directory, but providing that extra level allows us to organize our helpers in good shape, specifically when you’re going to have plenty of them.

The file starts with a pretty standard namespace declaration:

The purpose of our custom helper is to retrieve a username based on a userid. Hence, we need to interact with the database, and that forces us to include DB Facade.

For those who are not familiar with Laravel Facades, it’s just another convenient way to access the objects in service containers. Alternatively, you could have used dependency injection.

Moving ahead, there comes the concrete implementation of our helper. As you can see, there’s a static method that defines the logic of retrieving a username based on a userid.

The $user object holds the database record with the matching userid. Finally, the method returns the username as a response in the following statement.

That’s it as far as our helper file is concerned.

Now we’ve created our helper file, but the question is how are you going to use it? Two quick solutions come to my mind:

  • You can include our helper filename in the composer.json, so that it gets auto-loaded. Then, you could straight away call the static method of our helper class.
  • You can go ahead and create a Laravel service provider that allows you to register your custom helper file so that the Laravel framework loads it along with other dependencies. Register that service provider in the Laravel configuration and create an alias to use your helper.

Of course, the first one is pretty quick and easy to implement, and you might be tempted to do so, but I would rather suggest the latter one as it looks like more of an artisan way and is more maintainable.

Move to the command line and run the following command in your application root to create a new service provider.

You should see the message that confirms that it’s created successfully under the app/Providers directory.

Open that file and you should already see two methods out there. The important one in the context of this article is the register method. Yes, it’s empty at the moment, so let’s feed in some stuff to make it more useful.

The register method is used to register your dependencies, and we’ve exactly done that. We’ve included our custom helper file.

Here’s how the app/Providers/EnvatoServiceProvider.php file should look after modifications.

So it’s all pretty good so far. We have our custom helper and service provider on the table.

Next, we need to inform Laravel about our service provider so that it can load it during bootstrapping. Let’s open the config/app.php and add the following entry in the providers array at the end.

To use our helper in a convenient way, we could create an alias as well. So let’s do that by adding the following entry in the aliases array at the end in the same file.

By defining this entry, we can call our helper by using the EnvatoUser keyword. Pretty convenient, huh? For your reference, here’s the complete config/app.php file.

We’re almost there! We’ve done all the hard work to get here, and now we can reap the benefits of our custom helper.

Your First Custom Helper in Action

Again, to keep things simple and straightforward, we’ll define a basic Laravel route and call our helper from there!

Go ahead and create a routes/web.php file with the following contents.

Does that need any explanation at all? We’ve just called the custom helper by the shorthand EnvatoUser::get_username, and it should return the username.

Of course, you can call our helper from anywhere in the application, be it a controller or view.

So that ends our story for today.

Conclusion

Helpers in Laravel are really a powerful feature, and I'm sure that as a developer you would love to extend that. And that was the topic of today—we went through the basics of the Laravel helper file structure and created a useful custom helper.

I hope you’ve enjoyed the article and it helps you create your own custom helpers in day-to-day Laravel application development.

Don’t hesitate to leave your comments and queries in the feed below. I also catch comments on my Twitter and respond to them as soon as I can!

Tags:

Comments

Related Articles