Laravel Middleware - A Complete guide
Create a Middleware, Pass Parameter in Middleware.

Laravel | VueJs | PHP | Shopify | ReactJs | MySql
Search for a command to run...
Create a Middleware, Pass Parameter in Middleware.

Laravel | VueJs | PHP | Shopify | ReactJs | MySql
No comments yet. Be the first to comment.
Eloquent Factory & DB Seeder

Log in without a password by using the magic link in Laravel.

Verify Registered Mobile Number

Login with username / Mobile No / UUID

Upload image & Store in Public, Store or AWS S3.

Today we will take a detailed look into Laravel Middleware, and will understand its use of it.
A Middleware is like a bridge between HTTP requests and responses. it provides a mechanism for inspecting and filtering HTTP requests entering your application.
Let's understand the Middleware by jumping into the code directly. After Installing Laravel let's see how we can create and use Middleware.
For creating a middleware we have to run a command, Let's say for creating a middleware to check the year in request named 'CheckYear'.
php artisan make:middleware CheckYear
Let's Add a logic to add conditions in Middleware to check the year.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckYear
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @param String $year
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, $year)
{
if($request->has('year') && ($request->year == $year)){
return $next($request);
}
return redirect()->route('welcome');
}
}
routes/web.phpRoute::get('/user/create', [App\Http\Controllers\UserController::class, 'createUser'])->middleware(['check-year:2022']);
Route::get('/user/new', [App\Http\Controllers\UserController::class, 'createUser'])->middleware(['check-year:2023']);
You can create any other middleware and use it as per your requirement.
Here you will get a complete video tutorial on Youtube.
If you face any issues while implementing, please comment on your query.
Thank You for Reading