DEV Community

Cover image for Laravel 9 Middleware - A Complete Guide
shani singh
shani singh

Posted on

Laravel 9 Middleware - A Complete Guide

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

What is Middleware ?

A Middleware is like a bridge between HTTP request and response. it provide 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 year in request named 'CheckYear'.

php artisan make:middleware CheckYear
Enter fullscreen mode Exit fullscreen mode

Add a condition to Middleware

Let's Add a logic to add condition in Middleware to check 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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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']);
Enter fullscreen mode Exit fullscreen mode

You can create any other middleware and use it as per your requirement.

Here you will get complete video tutorial on Youtube.

If you face any issues while implementing, please comment your query.

Thank You for Reading

Reach Out To me.
Twitter
Instagram
YouTube

Top comments (0)