Create Custom Helper function in Laravel

236
laravel-custom-helper-function

Laravel provides many helper functions by default which can be used globally in any project. Some of the most used helper functions are app_path(), storage_path(), public_path(), dd, csrf_token() and so on. In this article, we will create our own custom helper function in Laravel. We will create global functions that can be used anywhere within the project.

We can create our custom helper function using two methods. We will discuss about both of them in this article.

Method 1

In this method, we will create a helpers.php file and autoload it inside composer.json. The location of the helpers.phpcan be anywhere within your as long as the path to autoload in the composer.json is correct. But, I would like to create it inside app/Helpers/ directory. Let’s create the file inside this directory and write a function to convert the date format from dd/mm/yyyy to yyyy-mm-dd format.

<?php

//app/Helpers/helpers.php

//function to convert date format dd/mm/yyyy to yyyy-mm-dd
if (!function_exists('change_date_format')) {
    function change_date_format(String $date){
        $date = str_replace('/', '-', $date);

        return date('Y-m-d', strtotime($date));
    }
}

Now, we have our custom helper function but we need to autoload it so that we can use this function anywhere within our project. To autoload this file, we need to give the path of this file in composer.json. Inside composer.json autoload, add the path of the helpers.php file in files array. If the path of the helpers.php file you created is different than the one mentioned above, you need to give the correct path accordingly.

Note: If you have more than one helper file, you need to autoload each file in composer.json file

Our final composer.json file looks like below.

//composer.json

.........
"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    },
    "files": [
        "app/Helpers/helpers.php"  <- Added file path

    ]
},
..........

We are almost done. One final step is to run a command so that our application can autoload the files as specified in the composer.json.

//command

php artisan dump-autoload

Our helper function is ready to use. We can call it from anywhere within our application. An example is shown below.

<?php

//in controller
$date = change_date_format('14/02/2022');

//in blade
{{ change_date_format('14/02/2022') }}

Method 2

We can also same functionality using a service provider. First of all, create a service provider with the below command. This will create a new file inside app/providers directory.

//command

php artisan make:provider HelperServiceProvider

If we open up our HelperServiceProvider file, we see two empty methods. We will be using the register() method. We add some code inside the register() function.

/**
 * Register services.
 *
 * @return void
 */
public function register()
{
    $files =glob(app_path('Helpers').'/*.php');  //get files list from helpers directory
    foreach ($files as $file) {
        require_once($file);    //require helper file
    }
}

Now, we have our service provider ready. Our next step is to load this service provider when the application load. For this, we need to add this service provider to the providers’ list. Open up your config/app.php file and add the provider class list.

<?php


//config/app.php

'providers' => [
    .........
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,

    App\Providers\HelperServiceProvider::class  //added here
],

The final step is to create the helper functions. We will create the same date conversion function inside app/Helpers directory.

<?php

//app/Helpers/helpers.php

//function to convert date format dd/mm/yyyy to yyyy-mm-dd
if (!function_exists('change_date_format')) {
    function change_date_format(String $date){
        $date = str_replace('/', '-', $date);

        return date('Y-m-d', strtotime($date));
    }
}

Voila!!! Our helper function is ready to use within the application. We can use the helper as mentioned. That is all about creating custom helper function in Laravel. Don’t forget to drop your thoughts in the comment below 🙂 .

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.