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

Uncategorized Custom middleware in laravel

How to create custom middleware Laravel 8

October 15, 2021November 6, 2023

In this tutorial we will going to learn custom middleware Laravel 8. Middleware are used to create a layer between request and response of the http request. it filters or create a logic before the request serve to the controller and also filter or modify the response. we can also…

Read More
Php Laravel whereHas

Laravel whereHas in eloquent Model Example

October 2, 2022March 16, 2024

In this blog post, we’ll take a look at Laravel whereHas in eloquent Model Example and advantages. whereHas method is an important part of the Eloquent ORM. It allows you to add a constraint to a relationship query. whereHas method can be used to filter records based on a relationship….

Read More
Devops install php 8 in ubuntu

How to install PHP 8.0 in Ubuntu 20.04 LTS ?

September 18, 2021November 5, 2023

In this tutorial we will learn to install PHP 8.0 on Ubuntu 20.04 LTS using PPA. PHP 8.0 is the latest version of php and it have many upgrades. Installation process is same as How to install PHP on Ubuntu? or How to Install multiple/different version of PHP? Step 1…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version