Routing

Defining and managing routes in Laravel

graph TD A[HTTP Request] --> B[Route Matcher] B --> C{Route Found?} C -->|Yes| D[Check Middleware] C -->|No| E[404 Not Found] D --> F[Execute Handler] F --> G{Type?} G -->|Closure| H[Execute Closure] G -->|Controller| I[Controller Action] H --> J[Response] I --> J K[Route Groups] --> B L[Route Parameters] --> B M[Route Constraints] --> B

Routing in Laravel means mapping URLs to Controller actions or closures. Laravel's routing system is one of the most powerful and flexible routing systems in PHP that allows you to easily define RESTful and complex URLs.


Route Types:


1. GET: For retrieving data and displaying pages
2. POST: For sending data and creating new resources
3. PUT/PATCH: For updating resources (PUT for full update, PATCH for partial update)
4. DELETE: For deleting resources
5. ANY: For all HTTP methods
6. MATCH: For specific methods
7. RESOURCE: For RESTful resource routes


Advanced Features:


  • <strong>Route Parameters</strong>: Receiving parameters from URL
  • <strong>Optional Parameters</strong>: Optional parameters
  • <strong>Route Constraints</strong>: Validating parameters with regex
  • <strong>Named Routes</strong>: Naming routes for easy access
  • <strong>Route Groups</strong>: Grouping routes with shared prefix, middleware and namespace
  • <strong>Route Prefix</strong>: Adding prefix to all routes in a group
  • <strong>Route Middleware</strong>: Applying middleware to specific routes
  • <strong>Route Model Binding</strong>: Automatically binding model to route parameter
  • <strong>Route Caching</strong>: Caching routes for performance improvement
  • <strong>Route Subdomain</strong>: Managing routes based on subdomain
  • <strong>Route Domain</strong>: Managing routes based on domain

Examples

Simple Route

Route::get('/users', function () {
    return 'All users';
});

A simple route that responds to GET request to /users.

Route with Parameter

Route::get('/users/{id}', function ($id) {
    return "User ID: {$id}";
});

A route with parameter that receives user id.

Route to Controller

Route::get('/users', [UserController::class, 'index']);

Route that points to index method in UserController.

Route with Constraints

Route::get('/users/{id}', function ($id) {
    return User::find($id);
})->where('id', '[0-9]+');

// Multiple constraints
Route::get('/posts/{post}/comments/{comment}', function ($post, $comment) {
    //
})->where(['post' => '[0-9]+', 'comment' => '[0-9]+']);

Route with constraint that only accepts numbers.

Named Routes

Route::get('/users/{id}', [UserController::class, 'show'])
    ->name('users.show');

// Usage in code
return redirect()->route('users.show', ['id' => 1]);

// In Blade
<a href="{{ route('users.show', ['id' => 1]) }}">View User</a>

Named route that you can access by name.

Route Groups

Route::prefix('admin')->middleware('auth')->group(function () {
    Route::get('/users', [AdminController::class, 'users']);
    Route::get('/posts', [AdminController::class, 'posts']);
    // All routes have /admin prefix and auth middleware
});

// Multiple attributes
Route::prefix('api')
    ->middleware(['api', 'throttle:60,1'])
    ->namespace('App\Http\Controllers\Api')
    ->group(function () {
        Route::get('/users', [UserController::class, 'index']);
    });

Route group with shared prefix and middleware.

Resource Routes

// Creates 7 RESTful routes
Route::resource('users', UserController::class);

// GET    /users              index
// GET    /users/create       create
// POST   /users              store
// GET    /users/{user}       show
// GET    /users/{user}/edit  edit
// PUT    /users/{user}       update
// DELETE /users/{user}       destroy

// API Resource (without create/edit)
Route::apiResource('users', UserController::class);

// Partial resource
Route::resource('users', UserController::class)
    ->only(['index', 'show']);

Route::resource('users', UserController::class)
    ->except(['create', 'edit']);

Resource routes that create all CRUD operations.

Route with Subdomain

Route::domain('{account}.example.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        // $account is the subdomain
        return User::where('account', $account)->find($id);
    });
});

// Specific subdomain
Route::domain('admin.example.com')->group(function () {
    Route::get('/', [AdminController::class, 'index']);
});

Route with subdomain that can create multi-tenant application.

Route Caching

// Cache routes (production only)
php artisan route:cache

// Clear route cache
php artisan route:clear

// List all routes
php artisan route:list

// List routes with filters
php artisan route:list --path=api
php artisan route:list --method=GET

Route caching can improve performance by up to 50%.

Use Cases

  • Defining RESTful API endpoints
  • Creating multi-tenant application with subdomain routing
  • Managing admin and public routes separately
  • Creating route groups for modular architecture
  • Using route caching for performance improvement
  • Defining complex routes with constraints and parameters

Common Mistakes

  • Defining routes in closure instead of controller causing testing issues
  • Not using named routes causing hard-coded URLs
  • Defining duplicate routes causing conflicts
  • Not using route constraints causing security issues
  • Forgetting route caching in production
  • Using ANY route causing security risks

Best Practices

  • Use controller actions instead of closures
  • Always use named routes
  • Use route groups for organization
  • Use route constraints for validation
  • Use route caching in production
  • Organize routes in separate files
  • Use resource routes for RESTful APIs

Edge Cases

  • Route conflicts with similar routes
  • Optional parameters that may cause ambiguity
  • Route model binding with custom resolution
  • Route caching in development causing issues
  • Subdomain routing in local environment
  • Route parameters with special characters

Performance Notes

  • Route caching can reduce routing overhead by up to 50%
  • Using route groups can make route resolution faster
  • Route constraints can improve performance with early rejection
  • Use route caching in production, not in development
  • Route list command can be useful for debugging

Security Notes

  • Always use route constraints for validation
  • Don't use ANY route except in special cases
  • Ensure sensitive routes are protected with middleware
  • Use route model binding for automatic 404
  • Route caching should not expose sensitive information

Interview Points

  • What is the difference between PUT and PATCH?
  • How does route caching work?
  • How can you solve route conflicts?
  • What is the difference between resource and apiResource?
  • What are the benefits of route groups?
  • How can you implement subdomain routing?

Version Notes

  • Laravel 11.x: Improved performance in route resolution
  • Laravel 11.x: Better support for route model binding
  • Laravel 10.x: Improved route caching mechanism
  • Laravel 9.x: Added route list filters