This tutorial aims to provide a comprehensive understanding of route management in Laravel. By the end of this tutorial, you should be able to create and manage routes in Laravel effectively.
Routes in Laravel are defined in the file located at routes/web.php
. When a request comes in, Laravel matches the URL to the appropriate route in this file.
A basic Laravel route accepts a URI and a Closure, providing a very simple and expressive method of defining routes.
Route::get('/', function () {
return 'Hello, World!';
});
Here, when a GET
request is made to the application's root URL (/
), the string 'Hello, World!' is returned.
You can create routes for all HTTP methods supported by Laravel.
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
You can create routes with parameters by using {}
in your route definition.
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
Routes can also be named and grouped to make them more manageable.
Route::get('user/profile', function () {
//
})->name('profile');
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second Middleware
});
Route::get('user/profile', function () {
// Uses first & second Middleware
})->name('profile');
});
// A GET route
Route::get('/greet', function () {
return 'Hello, User!';
});
// A POST route
Route::post('/register', function () {
// Code to register a user
});
// Route with a parameter
Route::get('/user/{id}', function ($id) {
return 'User ID: '.$id;
});
// Named route
Route::get('/dashboard', function () {
// Code to display dashboard
})->name('dashboard');
// Route group
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Code to display all users
});
});
In this tutorial, we learned about routing in Laravel, how to create basic routes, routes for different HTTP methods, how to set up route parameters, and how to use route naming and route groups. This knowledge is critical to managing user requests and directing them to the appropriate controllers and methods.
GET
route for the URL /products
that returns the string "Product List".Solution:
php
Route::get('/products', function () {
return 'Product List';
});
POST
route for the URL /login
that echos "Login Successful".Solution:
php
Route::post('/login', function () {
echo 'Login Successful';
});
/admin
that includes the routes /dashboard
and /users
.Solution:
php
Route::prefix('admin')->group(function () {
Route::get('/dashboard', function () {
// Code to display dashboard
});
Route::get('/users', function () {
// Code to display all users
});
});
Keep practicing with different types of routes and explore more about route models binding and middleware for a deeper understanding.