I will explain what an helper function is and what it is used for?

A custom helper function is used to have an easy understandable code and they are designed to speed up and homogenize repetitive tasks. In other words, to make your life easier :). This function is not the main core of the application or even of any class.

Their purpose is global and they are declared public and static so that you can invoke it independently. They will get rid of duplicate code and you can use them anywhere in the application.

Hint! It should be mentioned that Laravel already contains a variety of auxiliary functions that you can apply in your projects and for this I recommend you to check beforehand, if the goal you want to achieve is found in one of the functions offered by the framework. You can see them all at this link.

As an example, I will try to create a function that adds a number of days to a chosen date.

First step:
I create the following file structure:
app/Helpers/helpers.php

Second step:
I desig the logic of the function:

if (!function_exists('add_days_to_date')) {
    /**
     * @param \Carbon\Carbon $date
     * @param $days
     * @return \Carbon\Carbon
     */
    function add_days_to_date(Carbon\Carbon $date, $days): \Carbon\Carbon
    {
        return $date->addDays($days);
    }
}

 

According to PHP coding standard, I write the name of the function (not to be confused with the method of a class) in lower case, delimited by underscore.

Third step:
I open composer.json file, in the root directory of the project. In the "autoload" key, I add the files in which I wrote the function / functions.

"autoload": {
         "files": [
            "app/Helper/helpers.php"
        ],

        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    }

 

Fourth step:
We run the composer dump-autoload command so that the created files are discovered.

At this point, you can use this feature anywhere in the app. Enjoy!

Comment

Leave a reply

You must be login to post comments.