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.
This article shows how to create helper function and how to access it in your Controller, Model, Blade or other areas.
In this example, I will show you a custom function that convert local time to UTC and UTC time to local time. My application needed this feature as it deals with a lot of timezones based on the user logged in to the site.
Now we we will dive in to steps to create your first custom helper function in Laravel 8.
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.
Read about How To Call Static Function From Helper In Laravel Blade File?
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply