Laravel 8 Create Custom Helper Example

Dec 14, 2021 . Admin



Hello Dev,

This example is how to create cutom helper using laravel 8?

Now let's see example of how to create cutom helper example. We will check how to create cutom helper. This is a short guide on create cutom helper in laravel 8. Here you will learn how to create cutom helper. Let's get started with how to create cutom helper in laravel 8.

Here i will give you many example how to create cutom helper using laravel 8.

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 - MyWebtuts.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>

It will help you...

#Laravel 8 #Laravel