In this tutorial, we’ll delve into creating custom middleware in Laravel 11. Middleware serves as a crucial intermediary between incoming HTTP requests and their corresponding responses. It allows us to filter requests, apply logic before they reach the controller, and even modify the responses.
One common use case is validating user authentication or manipulating JSON requests and responses. Custom middleware provides flexibility to tailor these processes according to specific application needs.
Let’s explore an example where we implement middleware to check if a user status is not blocked by an admin. If the user is blocked by an admin, the middleware will handle the response accordingly.
Laravel offers numerous scenarios where custom middleware proves invaluable, such as applying middleware to custom requests in Laravel, creating middleware specific to APIs, and various other Laravel middleware examples tailored to specific functionalities
Steps to create Custom middleware Laravel
Creating custom middleware in Laravel involves several straightforward steps. Here’s a step-by-step guide to creating custom middleware
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 Inside the app/Http/Middleware
directory (create it if it doesn’t exist), create a new PHP file for your middleware. You can name it anything you like, for example.
<?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');
}
}
?>