LARAVEL LARAVEL Routing & Middleware 1 — Questions and Answers
Question 1: Which file is the primary location for defining web routes in a Laravel application?
- routes/web.php (Correct answer)
- routes/api.php
- app/Http/routes.php
- config/routes.php
Correct answer: routes/web.php
In Laravel, routes/web.php contains routes for the web interface with session state and CSRF protection.
Question 2: Which HTTP verb method would you use to define a route that only responds to DELETE requests?
- Route::delete() (Correct answer)
- Route::remove()
- Route::destroy()
- Route::erase()
Correct answer: Route::delete()
Route::delete() registers a route that responds exclusively to the HTTP DELETE verb.
Question 3: What does the `middleware` method do when chained onto a route definition in Laravel?
- Assigns middleware to filter the request before it reaches the controller (Correct answer)
- Caches the route response
- Logs the request to the database
- Validates the request payload
Correct answer: Assigns middleware to filter the request before it reaches the controller
Chaining ->middleware() on a route assigns one or more middleware classes that intercept and filter the HTTP request.
Question 4: How do you define a named route in Laravel?
- Route::get('/path', 'Controller@method')->name('route.name') (Correct answer)
- Route::name('route.name')->get('/path', 'Controller@method')
- Route::get('/path', 'Controller@method', 'route.name')
- Route::named('route.name', '/path', 'Controller@method')
Correct answer: Route::get('/path', 'Controller@method')->name('route.name')
Named routes are created by chaining the ->name() method onto the route definition.
Question 5: Which command generates a new middleware class in Laravel?
- php artisan make:middleware MiddlewareName (Correct answer)
- php artisan create:middleware MiddlewareName
- php artisan generate:middleware MiddlewareName
- php artisan middleware:make MiddlewareName
Correct answer: php artisan make:middleware MiddlewareName
The php artisan make:middleware command scaffolds a new middleware class in app/Http/Middleware/.
Question 6: Where must you register a custom middleware in Laravel to apply it globally to every HTTP request?
- In the $middleware array inside app/Http/Kernel.php (Correct answer)
- In the routes/web.php file
- In the config/app.php providers array
- In the .env file under MIDDLEWARE key
Correct answer: In the $middleware array inside app/Http/Kernel.php
Global middleware is registered in the $middleware property of the HTTP Kernel class.
Which file is the primary location for defining web routes in a Laravel application?