In Laravel, if a global middleware returns a response before calling $next($request), what is the effect on the request lifecycle?
public function handle($request, Closure $next)
{
if ($request->header('X-Block')) {
return response('Blocked by middleware', 403);
}
return $next($request);
}Think about what happens if middleware returns a response without calling the next middleware.
When a global middleware returns a response early, Laravel stops processing further middleware and the controller. The response is sent immediately to the client.
Which option correctly registers a global middleware in Laravel's app/Http/Kernel.php file?
protected $middleware = [
\App\Http\Middleware\CheckAge::class,
];Remember the correct way to reference a class with namespace in PHP arrays.
In PHP, class names with namespaces must be prefixed with a backslash and end with ::class to get the fully qualified class name. The array must have commas after each element.
Given this global middleware that adds a header, what will the client receive?
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-Global', 'Active');
return $response;
}Think about how middleware can modify the response after calling $next.
Middleware can modify the response object after calling $next($request). Here it adds a custom header before returning the response.
Consider this global middleware registered in Kernel.php. It does not run for routes using the 'api' middleware group. Why?
protected $middleware = [
\App\Http\Middleware\CheckUser::class,
];
protected $middlewareGroups = [
'web' => [
// web middleware
],
'api' => [
'throttle:api',
'auth:api',
],
];Recall how Laravel applies global middleware versus middleware groups.
Global middleware runs for every HTTP request regardless of middleware groups. If the middleware does not run, the problem is likely in the middleware logic or route definition, not in registration.
In Laravel, when a request is handled, in what order are global middleware and route middleware executed?
Think about the middleware layers and their scope in Laravel.
Laravel runs global middleware first on every request. Then it runs any route middleware assigned to the route. Finally, the controller handles the request.