Hello developer, In this guide, I'll walk you through the process of creating custom helper functions in Laravel 11. Laravel is an amazing PHP framework that simplifies web development, and creating custom helper functions can make your coding experience even smoother.
In this article, we'll create a custom helper function in laravel. So, you can easily use the anywhere in the laravel 11 application.
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel laravel-11-example
After that, we'll create a helpers.php file and create functions to that file.
app/Helpers/helpers.php
<?php
use Carbon\Carbon;
/**
* Write code on Method
*
* @return response()
*/
if (! function_exists('convertYmdToMdy')) {
function convertYmdToMdy($date)
{
return Carbon::createFromFormat('Y-m-d', $date)->format('m-d-Y');
}
}
/**
* Write code on Method
*
* @return response()
*/
if (! function_exists('convertMdyToYmd')) {
function convertMdyToYmd($date)
{
return Carbon::createFromFormat('m-d-Y', $date)->format('Y-m-d');
}
}
In this step, we'll specify the path to the helpers file. To do this, open the composer.json
file and add the following code snippet.
composer.json
...
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/Helpers/helpers.php"
]
},
...
Then, run the following command to load the helper.php file.
composer dump-autoload
Now, we'll define the routes into the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('date-convert', function(){
$mdY = convertYmdToMdy('2024-03-27');
var_dump("Converted into 'MDY': " . $mdY);
$ymd = convertMdyToYmd('03-27-2024');
var_dump("Converted into 'YMD': " . $ymd);
});
Then, run the laravel application using the following command.
php artisan serve
You might also like: