Creating your own helper file for Laravel

Laravel provides tons of helper functions to the users that are convenient for doing many things in your laravel application. You can find the default helper functions provided by laravel in the docs.

Today we’re going to learn how to make our own helper functions for our laravel application. The most common and generally used locations to create and store the helper files are :

  1. app/helpers.php
  2. app/Http/helpers.php

However you can organize and locate your helper file anywhere as your preferences. We are going to follow the 2nd suggested location app/Http/helpers.php.

You can make name your helper file anything you want which can be noticeable. Most commonly used names are :

  1. helpers.php
  2. NAME_OF_YOUR_PROJECT.php

We are going with helpers.php.

Let’s create helpers.php in our app/Http folder.

After creating a helper file, go to your composer.json file, where you can see an autoload and autoload-dev keys.

You see , we defined files key with an path array.

“files”: [ “app/Http/helpers.php” ]

Now the last things to do is to dump your autoloader.

go to your Console or terminal and go to your project directory and enter this command :

composer dump-autoload

Your helper file is ready , your helper file will be loaded automatically on every request because laravel requires Composer’s autoloader in file : public/index.php

Hence, now you can create your own helper functions for your application and use it. Before creating helper functions , please check if it’s already available as per your requirements. If not feel free to make your helper functions.

If you are still confused on how to create helper functions in your helper.php file, you can check these simple example out.

Sharing is caring!

Related Post