LARAVEL LARAVEL Routing & Middleware 2 — Questions and Answers
Question 1: What does `Route::group()` allow you to do in Laravel?
- Share route attributes like prefix and middleware across multiple routes (Correct answer)
- Bundle routes into a compiled cache
- Create resourceful route collections
- Limit route execution time
Correct answer: Share route attributes like prefix and middleware across multiple routes
Route::group() lets you share attributes such as middleware, prefix, or namespace across a set of routes.
Question 2: Which method is used to generate a URL for a named route in a Laravel Blade template?
- route('route.name') (Correct answer)
- url('route.name')
- path('route.name')
- link('route.name')
Correct answer: route('route.name')
The route() helper function generates a URL for a given named route in both Blade templates and PHP code.
Question 3: What is the purpose of route model binding in Laravel?
- Automatically inject a model instance into a route based on a URI segment (Correct answer)
- Bind a route to a specific database connection
- Map route parameters to config values
- Cache Eloquent query results per route
Correct answer: Automatically inject a model instance into a route based on a URI segment
Route model binding automatically resolves and injects an Eloquent model whose key matches the route segment.
Question 4: What does `Route::resource()` automatically create in Laravel?
- Seven RESTful routes mapping to controller methods (index, create, store, show, edit, update, destroy) (Correct answer)
- A database migration for the resource
- An API controller with JSON responses
- A service provider for dependency injection
Correct answer: Seven RESTful routes mapping to controller methods (index, create, store, show, edit, update, destroy)
Route::resource() generates the standard seven CRUD routes tied to a resourceful controller in a single declaration.
Question 5: Which middleware is responsible for protecting routes against Cross-Site Request Forgery in Laravel?
- \App\Http\Middleware\VerifyCsrfToken (Correct answer)
- \App\Http\Middleware\Authenticate
- \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth
- \Illuminate\Session\Middleware\StartSession
Correct answer: \App\Http\Middleware\VerifyCsrfToken
The VerifyCsrfToken middleware checks every POST/PUT/PATCH/DELETE request for a valid CSRF token.
Question 6: How do you define an optional route parameter in Laravel?
- By appending a ? to the parameter name, e.g. {param?} (Correct answer)
- By wrapping it in brackets, e.g. [param]
- By using an asterisk, e.g. {param*}
- By setting a default in Route::defaults()
Correct answer: By appending a ? to the parameter name, e.g. {param?}
Adding a ? after the parameter name marks it as optional, and you must also provide a default value in the closure signature.
What does `Route::group()` allow you to do in Laravel?