How to Create Custom Middleware in Laravel
How to Create Custom Middleware in Laravel
Techsolutionstuff
·
Follow
2 min read
·
Mar 20, 2024
27
4
app/Http/Middleware/IsAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
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::user()->role_id != 1) {
return response()->json('Opps! You do not
have permission to access.');
}
return $next($request);
}
}
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.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';
});
});