Wednesday, August 7, 2024

How to Create Custom Middleware in Laravel 11

 

Create Middleware

Now, we’ll create middleware using the following command.

php artisan make:middleware IsAdmin

app/Http/Middleware/IsAdmin.php

<?php


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check() && Auth::user()->role != 'superadmin') {
            //return response()->json('Oops! You do not have permission to access.');
            return response()->view('errors.error', [], 403);
        }

        return $next($request);
    }
}





Step 3: Register Middleware

In this step, we will register our custom middleware in the app.php file, as illustrated in the code snippet below:

bootstrap/app.php




<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\SuperAdminMiddleware;
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {

        $middleware->alias([
            'isAdmin' => \App\Http\Middleware\IsAdmin::class,
        ]);
   
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();



routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::middleware(['isAdmin'])->group(function () {
Route::get('/dashboard', function () {
return 'Dashboard';
});

Route::get('/users', function () {
return 'Users';
});
});

2 comments:

  1. This tutorial is still super helpful for setting up middleware in Laravel. its just been a bout a year but love how the process hasn’t changed much, how it remains efficient and effective!
    data science internship |
    python internship |
    artificial intelligence internship |
    java internship |
    cyber security internship

    ReplyDelete
  2. Thank you so much for sharing such insightful content! It’s rare to find posts that genuinely add value to the community, and I truly appreciate the effort put into this.
    Speaking of adding value, if you’re feeling overwhelmed by your daily workload, Meet My Assistant is here to help you scale. Whether it's managing your socials, handling emails, or streamlining operations, our expert virtual marketing assistant services are designed to give you your time back. We focus on the heavy lifting so you can focus on the big wins!
    Ready to level up? Reach out to us at contact@meetmyassistant.com or give us a ring at (786) 859-8131. Let’s make your business goals a reality together!

    ReplyDelete

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide If you're looking to host a Laravel project on Hostinger’s hPa...