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';
});
});

No comments:

Post a Comment

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...