Laravel Routing & Controllers Interview Questions
Comprehensive laravel routing & controllers interview questions and answers for Laravel. Prepare for your next job interview with expert guidance.
Questions Overview
1. What is routing in Laravel?
Basic2. What are the basic HTTP methods supported in Laravel routes?
Basic3. What is a controller in Laravel?
Basic4. How do you create a basic controller in Laravel?
Basic5. What is a route parameter?
Basic6. How do you name a route in Laravel?
Basic7. What is the purpose of web.php vs api.php routes?
Basic8. How do you access request data in a controller?
Basic9. What is route grouping?
Basic10. How do you redirect from a route?
Basic11. What are resource controllers and how are they used?
Moderate12. How do you implement route model binding in Laravel?
Moderate13. What are controller middleware and how are they implemented?
Moderate14. How do you handle file uploads in Laravel controllers?
Moderate15. What are route constraints and how are they used?
Moderate16. How do you handle CORS in Laravel routes?
Moderate17. What is dependency injection in controllers and how does it work?
Moderate18. How do you handle API versioning in Laravel routes?
Moderate19. What are signed routes and when should they be used?
Moderate20. How do you handle rate limiting in Laravel routes?
Moderate21. How do you implement custom route model binding resolution?
Advanced22. How do you implement domain routing and subdomain routing in Laravel?
Advanced23. How do you implement custom response macros?
Advanced24. How do you implement route caching in production?
Advanced25. How do you implement custom middleware parameters?
Advanced26. How do you implement route fallbacks and handle 404 errors?
Advanced27. How do you implement conditional middleware application?
Advanced28. How do you implement API resource collections with conditional relationships?
Advanced29. How do you implement route model binding with multiple parameters?
Advanced30. How do you implement route-model binding with soft deleted models?
Advanced1. What is routing in Laravel?
BasicRouting in Laravel refers to defining URL paths that users can access and mapping them to specific controller actions or closure callbacks. Routes are defined in files within the routes directory, primarily in web.php and api.php.
2. What are the basic HTTP methods supported in Laravel routes?
BasicLaravel supports common HTTP methods: GET for retrieving data, POST for creating new resources, PUT/PATCH for updating existing resources, DELETE for removing resources. These can be defined using Route::get(), Route::post(), Route::put(), Route::patch(), and Route::delete().
3. What is a controller in Laravel?
BasicA controller is a PHP class that handles business logic and acts as an intermediary between Models and Views. Controllers group related request handling logic into a single class, organizing code better than closure routes.
4. How do you create a basic controller in Laravel?
BasicControllers can be created using the Artisan command: php artisan make:controller ControllerName. This creates a new controller class in app/Http/Controllers directory with basic structure and necessary imports.
5. What is a route parameter?
BasicRoute parameters are dynamic segments in URLs that capture and pass values to controller methods. They are defined using curly braces in route definitions, like '/user/{id}' where {id} is the parameter.
6. How do you name a route in Laravel?
BasicRoutes can be named using the name() method: Route::get('/profile', [ProfileController::class, 'show'])->name('profile'). Named routes provide a convenient way to generate URLs or redirects using route('profile').
7. What is the purpose of web.php vs api.php routes?
Basicweb.php contains routes for web interface and includes session state and CSRF protection. api.php is for stateless API routes, includes rate limiting, and is prefixed with '/api'. api.php routes don't include session or CSRF middleware.
8. How do you access request data in a controller?
BasicRequest data can be accessed using the Request facade or by type-hinting Request in controller methods. Example: public function store(Request $request) { $name = $request->input('name'); }
9. What is route grouping?
BasicRoute grouping allows you to share route attributes (middleware, prefixes, namespaces) across multiple routes. Routes can be grouped using Route::group() or using the Route::prefix() method.
10. How do you redirect from a route?
BasicRedirects can be performed using redirect() helper or Route::redirect(). Examples: return redirect('/home') or Route::redirect('/here', '/there'). You can also redirect to named routes using redirect()->route('name').
11. What are resource controllers and how are they used?
ModerateResource controllers handle CRUD operations for a resource. Created using 'php artisan make:controller ResourceController --resource', they provide methods like index(), create(), store(), show(), edit(), update(), and destroy(). They're bound to routes using Route::resource().
12. How do you implement route model binding in Laravel?
ModerateRoute model binding automatically resolves Eloquent models from route parameters. It can be implicit (type-hint the model) or explicit (define in RouteServiceProvider). Example: Route::get('/users/{user}', function (User $user) { return $user; }).
13. What are controller middleware and how are they implemented?
ModerateController middleware filter HTTP requests before they reach controllers. They can be assigned using the middleware method in controllers or in route definitions. They're defined in app/Http/Kernel.php and can be applied to specific methods using 'only' and 'except'.
14. How do you handle file uploads in Laravel controllers?
ModerateFile uploads are handled using the $request->file() method. Files can be stored using Storage facade or move() method. Example: if($request->hasFile('photo')) { $path = $request->file('photo')->store('uploads'); }
15. What are route constraints and how are they used?
ModerateRoute constraints limit how route parameters may be matched using regex patterns. They can be applied using where() method or globally in RouteServiceProvider. Example: Route::get('user/{id}')->where('id', '[0-9]+').
16. How do you handle CORS in Laravel routes?
ModerateCORS can be handled using the cors middleware and configuration in config/cors.php. Laravel provides built-in CORS support through the fruitcake/laravel-cors package. Headers and allowed origins can be configured as needed.
17. What is dependency injection in controllers and how does it work?
ModerateDependency injection in controllers automatically resolves class dependencies in constructor or method parameters through Laravel's service container. This enables better testing and loose coupling of components.
18. How do you handle API versioning in Laravel routes?
ModerateAPI versioning can be implemented using route prefixes, subdomains, or headers. Common approaches include using route groups with prefixes like 'api/v1/' or namespace-based versioning in different controllers.
19. What are signed routes and when should they be used?
ModerateSigned routes are URLs with a signature hash to verify they haven't been modified. Created using URL::signedRoute(), they're useful for email verification, temporary access links, or public sharing of protected resources.
20. How do you handle rate limiting in Laravel routes?
ModerateRate limiting is implemented using throttle middleware. It can be configured in RouteServiceProvider and customized using the RateLimiter facade. Limits can be set per minute/hour and customized per user or IP.
21. How do you implement custom route model binding resolution?
AdvancedCustom route model binding can be implemented by overriding the resolveRouteBinding() method in models or by defining custom binders in RouteServiceProvider's boot method using Route::bind().
22. How do you implement domain routing and subdomain routing in Laravel?
AdvancedDomain routing is implemented using Route::domain(). Subdomains can capture parameters: Route::domain('{account}.example.com')->group(function () {}). Wildcard subdomains and pattern matching are supported.
23. How do you implement custom response macros?
AdvancedCustom response macros extend Response functionality using Response::macro() in a service provider. Example: Response::macro('caps', function ($value) { return Response::make(strtoupper($value)); });
24. How do you implement route caching in production?
AdvancedRoute caching improves performance using 'php artisan route:cache'. It requires all route closures to be converted to controller methods. Route cache must be cleared when routes change using 'route:clear'.
25. How do you implement custom middleware parameters?
AdvancedCustom middleware parameters are implemented by adding additional parameters to handle() method. In routes: ->middleware('role:admin,editor'). In middleware: handle($request, $next, ...$roles).
26. How do you implement route fallbacks and handle 404 errors?
AdvancedRoute fallbacks are implemented using Route::fallback(). Custom 404 handling can be done by overriding the render() method in App\Exceptions\Handler or creating custom exception handlers.
27. How do you implement conditional middleware application?
AdvancedConditional middleware can be implemented using middleware() with when() or unless() methods. Can also be done by logic in middleware handle() method or by creating custom middleware classes with conditions.
28. How do you implement API resource collections with conditional relationships?
AdvancedAPI resource collections with conditional relationships use whenLoaded() method and conditional attribute inclusion. Custom collection classes can be created to handle complex transformations and relationship loading.
29. How do you implement route model binding with multiple parameters?
AdvancedMultiple parameter binding can be implemented using explicit route model binding in RouteServiceProvider, or by implementing custom resolution logic in resolveRouteBinding(). Supports nested and dependent bindings.
30. How do you implement route-model binding with soft deleted models?
AdvancedSoft deleted models in route binding can be included using withTrashed() scope. Custom resolution logic can be implemented in resolveRouteBinding() to handle different scenarios of soft deleted models.