How To Create Custom Helper In Laravel 8

10-Apr-2023

.

Admin

How To Create Custom Helper In Laravel 8

Hello Friends,

This article is focused on laravel 8 custom helper functions. we will help you to give example of laravel 8 custom helpers. you can see laravel 8 create custom helper file.

we know laravel 8 also provide helper function for array, url, route, path etc. But not all function provided that we require. maybe some basic helper function like date format in our project. it is many time require. so i think it's better we create our helper function use everywhere same code.

So let's create helpers file in laravel 8 by using following steps.

Step 1 :


Create helpers.php File

app/helpers.php

<?php

function changeDateFormate($date,$date_format){

return \Carbon\Carbon::createFromFormat('Y-m-d', $date)->format($date_format);

}

Step 2:

Add File Path In composer.json File

composer.json

...

"autoload": {

"psr-4": {

"App\\": "app/",

"Database\\Factories\\": "database/factories/",

"Database\\Seeders\\": "database/seeders/"

},

"files": [

"app/helpers.php"

]

},

...

Step 3 :

Run Command

this is the last step, you should just run following command:

composer dump-autoload

Use In Route :

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\CustomHelperController;

Route::get('custom-helper', [CustomHelperController::class, 'index'])->name('custom.helper.index');

Use In Controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;

use Illuminate\Http\Request;

use App\Models\User;

class CustomHelperController extends Controller

{

/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

return view('customHelper');

}

}

Use In Blade File

app/resource/view

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How To Create Custom Helper In Laravel 8 - Nicesnippets.com</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<div class="row">

<div class="col-md-8 mt-5">

<p>Today Date : {{ $newDateFormat = changeDateFormate(date('Y-m-d'),'m/d/Y') }}</p>

</div>

</div>

</div>

</body>

</html>

Output:

Today Date : 11/01/2021

I hope it can help you...

#Laravel 8

#Css

#Html

#Bootstrap 4

#Bootstrap