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

Share this:

  • Facebook
  • X

Related

Php Laravel

Post navigation

Previous post
Next post

Related Posts

Php make a component in laravel 10

How to make component in Laravel 8 ?

December 8, 2021November 10, 2023

This tutorial demonstrates how to make component in Laravel 8 using Blade and simple html. Laravel offers a library to construct HTML components, much like Angular or React, that can accept parameters through HTML attrutes. These components can be used anywhere within our application and are independent of controller routes….

Share this:

  • Facebook
  • X
Read More
Php How to Upload image with preview in Laravel 9 with example

How to Upload image with preview in Laravel 9 with example ?

May 14, 2022May 14, 2022

Upload image with preview in laravel or for any website can be basic requirement like set up a profile picture to providing the documents. Laravel 9 provides robust functionality to upload and process the image with security. Laravel simply use Request file method to access the uploaded file and then…

Share this:

  • Facebook
  • X
Read More
Php How to Set Default Null Value in Laravel Migration

How to Set Default Null Value in Laravel Migration?

August 18, 2022August 18, 2022

To set default null value in laravel migration we use nullable method of schema class. As we learnt about How to Add Default Value to Column in Laravel Migration? in our last article but sometimes we want to set null value to column instead of any number or string. Null…

Share this:

  • Facebook
  • X
Read More

Leave a ReplyCancel reply

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 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • 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

  • How to Call Controller Method from Another Controller in Laravel ?
  • How to Get Domain Name in Laravel ?
  • How to Append Query String to Route in Laravel ?
  • How to Append URL Query Params to Pagination Laravel ?
  • How to Get Today Records in Laravel ?
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version