Laravel 8 Create Custom Helper Functions Tutorial
Oct 09, 2021 . Admin
Hi Guys,
Today, In this example, I would like to share with you how to create a custom helper example in laravel you can easily utilize add helper functions in laravel 8 application.
So, mainly you have to write repeated code in your laravel project so I think it's better we create our helper function use everywhere same code.
Here, I will give you a full example of laravel 8 create custom helper functions so follow my below steps.
Step 1: Download LaravelLet us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.
composer create-project laravel/laravel example-appStep 2: Create helpers.php File
First of all we need to integrate app/helpers.php in your laravel project put below following code.
Path : app/helpers.php<?php /** * Write Your Code.. * * @return string */ function changeDateFormate($date,$date_format){ return \Carbon\Carbon::createFromFormat('Y-m-d', $date)->format($date_format); } /** * Write Your Code.. * * @return string */ function thumbImagePath($image_name) { return public_path('images/blogs/'.$image_name); }Step 3: Add File Path In composer.json File:
In this step, you have to put the path of helpers file, so basically open composer.json file and put following code in that file:
Path : composer.json... "autoload": { "psr-4": { "App\\": "app/", "Database\\Factories\\": "database/factories/", "Database\\Seeders\\": "database/seeders/" }, "files": [ "app/helpers.php" ] }, ...Run Command
In this last step you shoud required following command.
composer dump-autoloadCreate Route
Now in this step we will use this custom helper function changeDateFormate() and thumbImagePath() in our web.php file.
Path : routes/web.phpRoute::get('helper', function(){ $imageName = 'mywebtuts.png'; $fullpath = thumbImagePath($imageName); dd($fullpath); }); Route::get('helper2', function(){ $newDateFormat = changeDateFormate(date('Y-m-d'),'m/d/Y'); dd($newDateFormat); });Output
"/var/www/html/blog/public/images/blogs/mywebtuts.png"
"10/09/2021"
So, you can use this helper function in your laravel blade file.
$imageName = 'mywebtuts.png'; $fullpath = thumbImagePath($imageName); print_r($fullpath);
{{ changeDateFormate(date('Y-m-d'),'m/d/Y') }}
It will help you...