Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks

What is Laravel 8 middleware ?

Aman Jain, November 6, 2021November 6, 2021

Laravel middleware is a mechanism to filter the http request and response. As the name implies that middleware so it’s middle between the request and response.

we can change or validate request and response using the Laravel middleware. There is so many use cases of middleware like authentication, validating token, change request paras, validating a request, validating csrf etc.

Creating a middleware

Creating a middleware is easy using make:middleware artisan command or we can create manually

Artisan command for make middleware

php artisan make:middleware middleware_name

Now, let’s create a middleware for our application

php artisan make:middleware CheckBlacklist

Above command will create a middleware CheckBlacklist in folder \app\http\Middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (auth()->user()->is_blacklisted == 1) {
            return response()->json('Your account is blacklisted by admin');
        }
        return $next($request);
    }
}

Here, we checked user is blacklisted by admin or not, if user is blacklisted then return the response with message.

Registering middleware

We have created middleware but not registered yet, so to register our new middleware with our Laravel application we need to register it in app/http/kernel.php 

Registering middleware globally

To register the middleware globally we need to assign it to $routeMiddleware property of app/Http/Kernel.php


use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel
{
    ....


    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $middleware = [
        ....
        'checkBlacklist' => \App\Http\Middleware\CheckBlacklist::class,
    ];
}

Middleware to specific routes

We can also assign routes to specific routes using $routeMiddleware property of app/Http/Kernel.php


use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel
{
    ....


    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'checkBlacklist' => \App\Http\Middleware\CheckBlacklist::class,
    ];
}

Attaching Middleware to route


Route::get('/create-post',[PostController::class, 'create'])->middleware(CheckBlacklist::class);

Multiple middleware to route


Route::get('/create-post',[PostController::class, 'create'])
->middleware([CheckBlacklist::class,SecoundMiddleware::class]);

Middleware to group of routes

Route::group(['middleware' =>CheckBlacklist::class ], function () {
    //
});

Parametrized Middleware

In some cases we need to pass the pass the param to middleware to check some specific conditions like user role for page. We just need to add a extra param to handle function.

Take a quick example, here $role is param

public function handle($request, Closure $next, $role)
{
    if (! $request->user()->hasRole($role)) {
        // Redirect...
    }

    return $next($request);
}

Ataching to the paramo to route

Route::post('edit-post/{id}', ['middleware' => 'role:editor', function ($id) {
    //
}]);
beenhere

Also Read :

Create custom middleware in Laravel 8

Related

Php Laravel

Post navigation

Previous post
Next post

Related Posts

Php How to use conditional orderby in Laravel 8

How to use conditional orderBy clause in Laravel 8 eloquent ?

February 12, 2022October 4, 2022

In Laravel sometimes while creating a eloquent or db builder query you wanted to apply the orderBy clause on basis of some conditions and to achieve it you may use if else condition but laravel 8 itself provides solution to handle such type of situations using when method. Laravel eloquent…

Read More
Php laravel multiple where condition in eloquent

How to use laravel multiple where condition with example ?

March 5, 2022November 8, 2023

In this article i will show you to use laravel multiple where condition in eloquent. In laravel we can create multiple where condition in several ways like using the array of array, associative column and value and using multiple where clause. Sometimes we wanted to use multiple and condition or…

Read More
Javascript Laravel Ajax Autocomplete Using Select2

Laravel Customized Autocomplete Options Using Select2

July 18, 2022July 18, 2022

In this article we will learn to use Laravel Customized Autocomplete Options Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. Autocomplete search is mostly work of javascript and…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version