Laravel Middleware - A Complete guide

Laravel Middleware - A Complete guide

Create a Middleware, Pass Parameter in Middleware.

Shani Singh's photo
Shani Singh
·Jun 9, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Today we will take a detailed look into Laravel Middleware, and will understand its use of it.

What is Middleware?

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.

How to Create a 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

Add a condition to Middleware

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');
    }
}

Apply Middleware in routes/web.php

Route::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

Reach Out To me. Twitter Instagram YouTube

Did you find this article valuable?

Support Shani Singh by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this