HTTP Middleware
Middleware provides a mechanism for filtering HTTP requests entering your application. Middleware can perform various tasks like authentication, CSRF protection, CORS headers, and more.
Run the Spark Command to create a new middleware:
php spark make:middleware AuthMiddleware
It will create a new middleware class in the app/Http/Middlewares
directory:
<?php
namespace App\Http\Middlewares;
use Spark\Contracts\Http\MiddlewareInterface;
use Spark\Http\Request;
class AuthMiddleware implements MiddlewareInterface
{
public function handle(Request $request, \Closure $next): mixed
{
if (is_guest()) {
return redirect('/login')
->with('error', 'You must be logged in to access this page.');
}
return $next($request);
}
}
Registering Middleware
Register middleware in bootstrap/middlewares.php
to make them available
application-wide:
<?php
/**
* Middleware configuration.
*
* @return array
* An associative array of middleware keys and class names.
*/
return [
'auth' => \App\Http\Middlewares\AuthMiddleware::class,
// ...
];
Assigning Middleware to Routes
Apply middleware to specific routes using the middleware key:
Route::get('admin/profile', [AdminController::class, 'profile'])
->middleware('auth');
Multiple middleware can be applied using an array:
Route::get('admin/profile', [AdminController::class, 'profile'])
->middleware(['auth', 'super']);
Middleware Groups
Apply middleware to a group of routes:
Route::group(['middleware' => ['auth']], function() {
Route::get('dashboard', [DashboardController::class, 'index']);
// More routes...
});
Create a Middleware that accept arguments
<?php
namespace App\Http\Middlewares;
use Spark\Contracts\Http\MiddlewareWithParametersInterface;
use Spark\Http\Request;
class RoleMiddleware implements MiddlewareWithParametersInterface
{
public function handle(Request $request, \Closure $next, ...$parameters): mixed
{
if (is_guest() || !in_array(user('role'), $parameters)) {
return abort(403, 'You do not have permission to access this page.');
}
return $next($request);
}
}
Apply middleware to specific routes using the middleware key:
Route::get('admin/profile', [AdminController::class, 'profile'])
->middleware('auth');
Multiple middleware can be applied using an array:
Route::get('dashboard', [DashboardController::class, 'index'])
->middleware('role:super,admin');
Tip: Middleware executes in the order they are listed in the array. Put more
general
middleware first and specific ones later.