Interview question
What is middleware in Laravel and how do you create one? Laravel में middleware क्या है और कैसे बनाएं?
Answer
Middleware acts as a filtering layer for HTTP requests entering your application - for example checking authentication before allowing access to a route.
php artisan make:middleware CheckAge
class CheckAge
{
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('home');
}
return $next($request);
}
}Register it in app/Http/Kernel.php, then apply it to routes:
Route::get('profile', function () {
// ...
})->middleware('checkage');| Middleware type | Example use case |
|---|---|
| Global | Runs on every request (e.g. TrimStrings) |
| Route | Applied to specific routes (e.g. auth) |
Middleware एक filtering layer है जो HTTP requests को application में आने से पहले check करता है - जैसे authentication check करना।
php artisan make:middleware CheckAge
class CheckAge
{
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('home');
}
return $next($request);
}
}Was this answer clear?