Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Custom middleware in laravel

How to create custom middleware Laravel 8

Aman Jain, 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 use it to validate the user auth, JSON request to manipulate the request and response.

In this example we will execute a user check with status in not block by admin. if it’s blocked by admin then show the response accordingly. There is so many cases of custom middleware of laravel like to apply in laravel middleware custom request, laravel custom middleware for api, all mentioned are the laravel custom middleware example.

Steps to create Custom middleware Laravel

Let’s begin with simple example and step by step process:

Before start i assume you well known to Laravel project creation step and creating controllers.

Step 1 : Create Middleware

First step is to create the middleware using the Laravel artisan command or manually, so open the terminal at project location and run below command

php artisan make:middleware CheckBlacklist

Above command will create a middleware at location app\Http\Controllers\Middleware or you can also create the same manually at same location without artisan command.

<?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)
    {
        return $next($request);
    }
}

Step 2: Register new middleware in kernal

Now, go to app/http/kernel.php and register the new middleware if you want this to register for all the http request otherwise you can skip this step


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,
    ];
}

Step 3: Implement the logic in middleware

We have created our custom middleware and defined in kernel, now it’s time e to implement the our core logic for check blacklisted user.

<?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 == 0) {
            return $next($request);
        }
        return response()->json('Your account is blacklisted by admin'); 
   }
}

Here, we added the simple logic to check is the user is blacklisted or not, if yes then show the response Your account is blacklisted by admin.

Step 4: Create the route and add middleware

It’s time to add our new middleware to the our route so we can validate the request.

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\PostController;
use App\Http\Middleware\CheckBlacklist;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

//or to group

Route::middleware(CheckBlacklist::class)->namespace('\App\Http\Controllers\Api')->group(function(){

Route::get("edit-post",[PostController::class, 'edit']);
});

here, we assigned middleware to a single route as well to the group.

Step 5: Create controller and method

Now, it’s time to test our implementation and create a controller

<?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 class PostController extends Controller
 {
     public function create()
     {
         response()->json('You are good to go');
     }
 }
?>

How to modify response in middleware in Laravel 8 ?

In the above steps we learn to filter and check the blacklist status of user, now we are going to modify our response.

<?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 == 0) {
            $response = $next($request); // this is response from controller 
            // change the response and send to browser
            $content = $response->getContent();

    // ... process widgets in $content

          return $response->setContent($content);
            
        }
        return response()->json('Your account is blacklisted by admin'); 
   }
}

here we added a extra variable $response which take the value of controller response

$response = $next($request);

Now, we can modify $response to send the browser.

Related

Uncategorized Laravel Php

Post navigation

Previous post
Next post

Related Posts

Php Use Soft Delete to Temporary (Trash) Delete the Records in Laravel

Use Soft Delete to Temporary (Trash) Delete the Records in Laravel ?

June 17, 2022June 17, 2022

In laravel we use Soft Delete to Temporary (Trash) Delete the Records. Soft delete in laravel is use to hide the record from users by keeping the data in the database. There is many purpose of soft delete like deleting the user for admin but keep all the information in…

Read More

Laravel OTP Login and Registration Without Password

September 1, 2022March 16, 2024

Today most of the applications are using laravel otp login and registration without password for ease of login and registration and also provides easy to login without remembering the password each time while login or register. In Laravel there is multiple ways to implement the login and registration like Laravel…

Read More
Php How to Update Enum Field Value using Laravel Migration

How to Update Enum Field Value using Laravel Migration ?

August 13, 2022March 16, 2024

Sometime after add the values in enum field we wanted to Update Enum Field Value using Laravel Migration so that we can work according to requirements. In our last article How to Create Enum Field in Laravel Migration ? we learnt to create the enum and today we are give…

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

  • August 2025
  • 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

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version