Laravel Routing
Routing in Laravel is a way to define how your application responds to different URLs. It allows you to map specific URLs to controller methods or directly return a response.
1. Basic Routing
Define routes inside the routes/web.php
file.
Route::get('/hello', function () {
return 'Hello, World!';
});
Visiting /hello in your browser will display "Hello, World!".
2. Route Methods
Laravel supports multiple HTTP methods:
- GET: Retrieve data.
- POST: Submit data.
- PUT/PATCH: Update data.
- DELETE: Remove data.
3. Route with Parameters
Use dynamic parameters in routes:
Route::get('/user/{id}', function ($id) {
return "User ID: " . $id;
});
Visiting /user/5 will return "User ID: 5".
4. Using Controllers
Instead of writing logic in routes, use controllers:
Route::get('/signup', [AuthController::class, 'signup']);
Create a controller with:
php artisan make:controller AuthController
5. Middleware in Routes
Middleware filters HTTP requests before they reach the controller.
Route::middleware('auth')->group(function () {
Route::get('/dashboard', function () {
return 'Dashboard';
});
});
All routes inside this group will require the auth
middleware.
6. Grouped Routes
Group similar routes using prefixes:
Route::prefix('admin')->group(function () {
Route::get('/dashboard', function () { return 'Admin Dashboard'; });
Route::get('/settings', function () { return 'Admin Settings'; });
});
All routes inside the group will be prefixed with /admin
.
7. Nested Route Groups with Middleware
You can apply middleware to multiple routes using Route::middleware()
:
Route::middleware('auth')->group(function () {
Route::get("/profile", [UserController::class, 'getProfile']);
Route::patch("/profile", [UserController::class, 'updateProfile']);
Route::controller(OrderController::class)->group(function () {
Route::group(['prefix' => '/orders'], function () {
Route::get('', 'listOrders');
Route::post('', 'createOrder');
Route::get('/{order}', 'getOrderById')->whereNumber('order');
Route::delete("/{id}", 'cancelOrder')->whereNumber('id');
Route::put("/{id}", 'updateOrder')->whereNumber('id');
});
});
});
8. API Routing
Define API routes in routes/api.php
:
Route::get('/users', function () {
return response()->json([
'users' => [['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob']]
]);
});
API routes do not use sessions and are stateless.
9. Route Model Binding
Automatically fetch a model instance based on a route parameter.
Route::get('/post/{post}', function (Post $post) {
return $post;
});
This will automatically retrieve the Post
model based on the given ID.
10. Routing to a View (for SPA Applications)
If your Laravel application serves a frontend as a single-page application (SPA), you can use the view()
helper to return a specific view for all routes except API endpoints.
Route::get('/{any}', fn() => view('app'))
->where('any', '.*')
->middleware("auth");
This route ensures that any request not matching API endpoints will be directed to the app
view, allowing the frontend framework (e.g., React, Vue, or Angular) to handle client-side routing.
11. Redirect Routes
You can redirect a route to another URL:
Route::redirect('/old-url', '/new-url');
Conclusion
Laravel routing makes it easy to manage how your application handles requests. Start experimenting with different routes, controllers, and middleware to create powerful applications.
Post a Comment
0Comments