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

Laravel Append Query String to Route in Laravel

How to Append Query String to Route in Laravel ?

November 22, 2023March 16, 2024

In this guide, we’ll explore the methods and best practices on append query string to route in Laravel. One common requirement is appending query strings to routes, a task often encountered when dealing with dynamic data and user interactions. Understanding Query Strings and Routes in Laravel Before diving into the techniques,…

Read More
Php How to Send Mail in Laravel 8 : 9 to multiple recipients, CC and without SMTP

How to Send Mail in Laravel 8 / 9 to multiple recipients, CC and without SMTP ?

May 11, 2022May 11, 2022

In this article i will show you to Send Mail in Laravel to multiple recipients, without view and without SMTP. We can send our mail to multiple recipients using the same to method with array collection with email and name. if you do not want to use SMTP then you…

Read More
Php Laravel CRUD with Search, Image and Pagination

Laravel CRUD with Search, Image and Pagination

July 1, 2022November 6, 2023

In this article i will learn laravel CRUD with Search, Image and Pagination in laravel. In this post we will not only cover the CRUD operation but also the validation on form, unique validation, image uploading and view the uploaded image, Flash messages, Search the uploaded data and many more….

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