Laravel - Routing

Laravel - Routing

Introduction

Routing in Laravel is how you define the paths (URLs) of your application and map them to the logic that should be executed when they are accessed. Laravel’s routing system is powerful, expressive, and supports everything from simple closures to complex controller actions and resourceful routes.

All route definitions are stored in the routes/ directory:

  • web.php → For web routes (sessions, CSRF protection, cookies).
  • api.php → For stateless API routes (no session or CSRF).
  • console.php → For Artisan command-line routes.
  • channels.php → For broadcasting channels.

 

1 - Laravel Basic Routes

 

// Simple route with closure
Route::get('/welcome', function () {
    return 'Welcome to Laravel!';
});
HTTP VerbRoute DefinitionDescription
GETRoute::get()Retrieve resources
POSTRoute::post()Create resources
PUT/PATCHRoute::put() / Route::patch()Update resources
DELETERoute::delete()Delete resources
ANYRoute::any()Accept any HTTP verb
MATCHRoute::match(['get', 'post'], ...)Accept specific verbs

 

2 - Route Parameters

Required Parameters:

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

 

Optional Parameters:

Route::get('/user/{name?}', function ($name = 'Guest') {
    return "Hello, " . $name;
});

 

3 - Named Routes

Route::get('/profile', [UserController::class, 'show'])->name('profile');

// Generate URL
$url = route('profile');

// Redirect
return redirect()->route('profile');

 

4 - Route Groups

A. Middleware Group

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

 

B. Prefix Group

Route::prefix('admin')->group(function () {
    Route::get('/users', [AdminController::class, 'users']);
});

 

C. Namespace Group (Laravel 7 and earlier)

Route::namespace('Admin')->group(function () {
    Route::get('dashboard', 'DashboardController@index');
});

 

5 - Route Model Binding

A. Implicit Binding

Route::get('/user/{user}', function (App\Models\User $user) {
    return $user;
});

 

B. Explicit Binding (in RouteServiceProvider)

Route::bind('user', function ($value) {
    return App\Models\User::where('name', $value)->firstOrFail();
});

 

6 - Resourceful Routes

Route::resource('posts', PostController::class);

Generates routes for:

  • index, create, store, show, edit, update, destroy

 

You can limit routes:

Route::resource('posts', PostController::class)->only(['index', 'show']);

Or exclude routes:

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

 

7 - API Resource Routes

– For APIs without create/edit (no views):

Route::apiResource('posts', PostController::class);

 

8 - Fallback Routes

– Handle all non-matching routes:

Route::fallback(function () {
    return response()->json(['message' => 'Page Not Found'], 404);
});

 

9 - Route Caching (for performance)

php artisan route:cache   # Cache routes
php artisan route:clear   # Clear cached routes

 

10 - Route Constraints

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

– For multiple constraints:

Route::get('/post/{slug}/{id}', function ($slug, $id) {
})->where(['slug' => '[a-z\-]+', 'id' => '[0-9]+']);

 

Summary

FeatureExample
Basic routeRoute::get('/', fn() => 'Home');
Parameter/user/{id}
Optional param/user/{name?}
Named route->name('profile')
GroupRoute::middleware('auth')->group()
Resource routeRoute::resource('posts', PostController::class)
FallbackRoute::fallback(fn() => response(...))

 

Laravel {"id":37,"topic_id":1,"name":"Routing and Controllers","slug":"routing-and-controllers","image":null,"description":null,"icon":null,"class":null,"color":null,"status":0,"order":0,"created_at":"2025-05-10T21:56:57.000000Z","updated_at":"2025-05-10T21:56:57.000000Z"} - List of Contents

Related Tutorials: