Basic Routing
Routing is how you tell Laravel what to do when a user visits a URL. It's the entry point of every request. Let's understand this step by step โ we'll start simple and build up.
In Laravel, routes are defined in the routes/web.php file. Each route maps a URL to a piece of code โ either a closure or a controller method.
Defining Routes
Here's the simplest possible route:
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/about', function () {
return 'This is the about page';
});
The first argument is the URI, the second is what happens when someone hits that URL. You can use get, post, put, patch, delete, or match for any HTTP method.
Route Parameters and Named Routes
Sometimes you need dynamic segments in your URLs. Route parameters make that easy:
Route::get('/users/{id}', function ($id) {
return "User {$id}";
});
Route::get('/posts/{post}/comments/{comment}', function ($post, $comment) {
return "Post {$post}, Comment {$comment}";
});
Named routes let you refer to routes by a name instead of a URL. This is super useful when you might change URLs later:
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
echo route('dashboard');
echo route('dashboard', ['id' => 1]);
Route Groups and Middleware
When you have multiple routes that share the same prefix or middleware, route groups keep things DRY:
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
return 'Admin users';
});
Route::get('/posts', function () {
return 'Admin posts';
});
});
Route::middleware('auth')->group(function () {
Route::get('/profile', function () {
return view('profile');
});
Route::post('/profile', function () {
return redirect('/profile');
});
});
The middleware method wraps routes in a middleware layer. The prefix method adds a common URL prefix. You can nest groups for even more control.