LARAVEL LARAVEL Routing & Middleware 3 — Questions and Answers
Question 1: What does the `throttle` middleware do in Laravel?
- Rate-limits the number of requests a client can make within a time window (Correct answer)
- Compresses HTTP responses
- Delays request processing
- Blocks requests from specific IP addresses
Correct answer: Rate-limits the number of requests a client can make within a time window
The throttle middleware applies rate limiting by restricting how many requests a client can send per minute using named rate limiters.
Question 2: Which method allows you to redirect a user to a named route in a Laravel controller?
- return redirect()->route('route.name') (Correct answer)
- return response()->route('route.name')
- return back()->route('route.name')
- return view()->route('route.name')
Correct answer: return redirect()->route('route.name')
The redirect()->route() method creates an HTTP redirect response pointing to the URL of a named route.
Question 3: What is a route prefix used for in Laravel route groups?
- Prepending a URI segment to all routes in the group (Correct answer)
- Naming all routes in the group automatically
- Setting the HTTP method for all grouped routes
- Adding authentication to all grouped routes
Correct answer: Prepending a URI segment to all routes in the group
The prefix option in Route::group() prepends a common URI segment to every route defined within that group.
Question 4: What does `Route::fallback()` do in Laravel?
- Handles any request that does not match any defined routes (Correct answer)
- Serves a cached version of the last matched route
- Redirects to the home page on 404
- Logs unmatched routes to the database
Correct answer: Handles any request that does not match any defined routes
Route::fallback() registers a route that is invoked when no other route matches the incoming request URI.
Question 5: How do you apply middleware to a controller's specific methods in Laravel?
- Call $this->middleware('auth')->only(['method1','method2']) in the constructor (Correct answer)
- Annotate controller methods with @middleware
- List methods in routes/middleware.php
- Define it in the handle() method of the middleware
Correct answer: Call $this->middleware('auth')->only(['method1','method2']) in the constructor
Controller middleware is applied per-method by calling $this->middleware() with ->only() or ->except() inside the constructor.
Question 6: What Artisan command caches all application routes to speed up route registration?
- php artisan route:cache (Correct answer)
- php artisan route:compile
- php artisan optimize:routes
- php artisan routes:save
Correct answer: php artisan route:cache
php artisan route:cache serializes all routes into a single cached file, reducing the overhead of route registration on each request.
What does the `throttle` middleware do in Laravel?