How to Create Custom Helper Function in Laravel 11

Techsolutionstuff
2 min readApr 4, 2024

--

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.

Step 1: Install Laravel 11

In this step, we’ll install the laravel 11 application using the following command.

composer create-project laravel/laravel laravel-11-example

Step 2: Create helpers.php File

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');
}
}

Step 3: Register File Path In composer.json File

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

Step 4: Add Route

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);
});

Step 5: Run the Laravel App

Then, run the laravel application using the following command.

php artisan serve

You might also like:

--

--

Techsolutionstuff

The Techsolutionstuff is to help for beginner programmers who want to start career in web development or learn web development technologies or languages.