Today, I would like to show you laravel 9 create custom helper functions. This post will give you a simple example of laravel 9 creating a global function. We will look at an example of laravel 9 create a custom helper file. Here you will learn laravel 9 to create a global helper file.
we know Laravel 9 also provides helper functions for array, URL, route, path, etc. but sometimes we may require more custom helper functions for our project. so we need to create our own custom helper file and define global functions that can easily use it.
Here, I will give you a few steps to show you how to create a custom helper function in laravel 9.
Step 1: Install Laravel 9
This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
Step 2: 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:
<?php
// use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('call-helper', function () {
$mdY = convertYmdToMdy('2022-02-12');
var_dump("Converted into 'MDY': " . $mdY);
$ymd = convertMdyToYmd('02-12-2022');
var_dump("Converted into 'YMD': " . $ymd);
});
<?php use Illuminate\Support\Facades\Route; /*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/ Route::get('call-helper', function(){ $mdY = convertYmdToMdy('2022-02-12'); var_dump("Converted into 'MDY': " . $mdY); $ymd = convertMdyToYmd('02-12-2022'); var_dump("Converted into 'YMD': " . $ymd);});
php artisan serve
http://localhost:8000/call-helper
string(32) "Converted into 'MDY': 02-12-2022" string(32) "Converted into 'YMD': 2022-02-12"