Middleware filters requests to check or modify them before they reach the main application. This helps with tasks like authentication, logging, or modifying headers.
If middleware denies a request, it stops the request from going further and sends a response immediately, like a 403 error for unauthorized access.
X-Custom-Header: Hello to every request. What will the controller receive?<?php
// Middleware handle method
public function handle($request, Closure $next) {
$request->headers->set('X-Custom-Header', 'Hello');
return $next($request);
}
// Controller method
public function index(Request $request) {
return $request->header('X-Custom-Header');
}The middleware sets the header before passing the request on, so the controller receives the modified header value "Hello".
Option A uses auth()->check() correctly to verify if the user is logged in. If not, it redirects to login. Other options have wrong methods or syntax.
public function handle($request, Closure $next) {
if (auth()->check()) {
return redirect('login');
}
return $next($request);
}The condition auth()->check() returns true for authenticated users, so it redirects them instead of blocking unauthenticated users. The logic is reversed.
