Routes are defined in the routes/web.php
file.
π Example: Simple GET Route
Route::get('/hello', function () {
return "Hello, Laravel!";
});
Visiting /hello
in the browser will display "Hello, Laravel!".
You can pass dynamic values using route parameters.
π Example: Route with a required parameter
Route::get('/user/{id}', function ($id) {
return "User ID: " . $id;
});
Visiting /user/5
will return "User ID: 5".
π Example: Providing a default value
Route::get('/user/{name?}', function ($name = 'Guest') {
return "Welcome, " . $name;
});
/user/Ali
→ "Welcome, Ali"/user/
→ "Welcome, Guest"Instead of defining logic inside web.php
, you can route to a controller method.
π Example: Using a Controller for Routing
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
This calls the index()
method in UserController
.
Laravel routing makes URL management simple and flexible.
π― Next Steps: Explore named routes, route groups, and middleware! π