Laravel 11 has brought improvements to its routing system, making it easier and cleaner to define routes for your web and API applications. In this guide, we’ll explore everything from simple routes to advanced features like middleware and route model binding.
1. Understanding Basic Routes #
In Laravel, routes are defined inside the routes/web.php file for web applications and routes/api.php for APIs.
Route::get('/', function () {
return 'Welcome to Laravel 11';
});
2. Passing Parameters to Routes #
You can pass parameters directly to routes:
Route::get('/user/{id}', function ($id) {
return "User ID: " . $id;
});
3. Route Groups #
Route groups allow you to share attributes like middleware, namespaces, and prefixes.
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', 'DashboardController@index');
});
4. Controller-Based Routes #
For cleaner code, point routes to controller methods:
Route::get('/profile', [ProfileController::class, 'show']);
5. Route Model Binding #
Laravel allows automatic injection of models into routes:
Route::get('/post/{post}', function (App\Models\Post $post) {
return $post;
});
6. API Routes #
For APIs, define routes inside routes/api.php:
Route::get('/users', [UserController::class, 'index']);
Conclusion #
Laravel 11's routing system offers flexibility and structure for modern web and API applications. By mastering these concepts, you can build scalable and maintainable projects with ease.