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 Laravel 11 Ajax Image Upload with form with example

Laravel 11 Ajax Image Upload with form with example

July 16, 2024July 16, 2024

In this tutorial, I will demonstrate how to implement Laravel 11 Ajax Image Upload with form. This can be achieved using Laravel’s file and storage providers. In our previous articles, such as How to Upload image in Laravel 11 ? we explained how to upload images without Ajax. However, today…

Read More
Php Integrate Google Map with Marker in Laravel

Integrate Google Map with Marker in Laravel

August 28, 2022March 16, 2024

In this article we will learn to integrate google map with marker in laravel. Google maps are used to share the location or indicate the location of business and any user. In our application we want to show the exact location so in that case google maps are most optimal…

Read More
Php Laravel ajax login and register

Laravel ajax login and registration with example

December 4, 2021November 12, 2023

In Laravel 8 there is multiple ways to implement the laravel Ajax login and registration like Laravel provides its own auth with packages Jetstream, passport,sanctum, breeze and fortify. These all packages are easy to install and configure but sometimes our application requirement and design patterns are different or we can…

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

  • 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

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version