30 Mar 2022

Laravel 8 Create Custom Helper Functions (Global Function)

This article helps you to create a custom helper function in Laravel. You may have noticed some functions in Larave do not need to import the classes, and it’s not attached with any class name, such as optional(), route() etc. These are so called helper functions.


Step 1 Create helpers.php File

In this step, you need to create app/Helpers/helpers.php in your laravel project and put the following code in that file:

app/Helpers/helpers.php

<?php
use Carbon\Carbon;

if (! function_exists('convertLocalToUTC')) {
    function convertLocalToUTC($time)
    {
        return Carbon::createFromFormat('Y-m-d H:i:s', $time, 'Europe/Paris')->setTimezone('UTC');
    }
}

if (! function_exists('convertUTCToLocal')) {
    function convertUTCToLocal($time)
    {
        return Carbon::createFromFormat('Y-m-d H:i:s', $time, 'UTC')->setTimezone('Europe/Paris');
    }
}

Step 2 Add new file path in composer.json file

We have to inform the system that we have added a new file to run everywhere in Laravel, so add the "files": ["app/Helpers/helpers.php"] to composer.json in the autoload block.

composer.json

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

 


Step 3: Run the composer autoload command

To take this changes in effect, just the below command from the root directory.

composer dump-autoload

You are alomost done with the configuration. To test this, create a new route in the routes/web.php and add the below code in there.

Route::get('newhelper', function(){
    $timeInEuropeParisTimezone = '2021-03-25 11:00:00';
    $timeInUTC = convertLocalToUTC($timeInEuropeParisTimezone);
  
    dd($timeInUTC);
});

Access your newly created route in browser, you will see this function called properly.

Even you can use this function in Blade Template:

{{convertLocalToUTC('2021-03-25 11:00:00')}}

That’s it for today, hope you had enjoyed the article.

No comments:

Post a Comment