Site Admin
Site Admin Founder of MeaningArticles
1514 Views

Laravel 8 How to create Custom Helper?

Hello dev.

this article helps you to create a custom helper function in Laravel. you may have noticed a few functions in Larave do now not want to import the classes, and it’s not connected with any class name, which includes optional(), route() etc. those are so called to as helper functions.

this article shows a way to create helper function and a way to access it in your Controller, model, Blade or different areas.

In this example, i will show you a custom function that convert local time to UTC and UTC time to local time. My utility wished this feature as it deals with a lot of timezones based on the user logged in to the website.

Now we are able to dive in to steps to create your first custom helper function in Laravel 8.


Step 1: Create helpers.php File

on this step, you need to create app/Helpers/helpers.php on 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've to inform the system that we've added a new file to run anywhere in Laravel, so add the "files": ["app/Helpers/helpers.php"] to composer.json within 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 carried out with the configuration. to test this, create a new route within 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 to your newly created route in browser, you'll see this function called properly.

Even you can use this function in Blade Template:

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

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.