DEV Community

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

Posted on

5 2

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay