Laravel Middleware - A Complete guide

Shani SinghShani Singh
2 min read

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

0
Subscribe to my newsletter

Read articles from Shani Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shani Singh
Shani Singh

Laravel | VueJs | PHP | Shopify | ReactJs | MySql