What are routes in Laravel?
- Routes define how Laravel responds to incoming HTTP requests.
- They map a URL to a Closure or a Controller action.
- Routes determine what code should execute when a user visits a specific URL.
- Laravel supports different HTTP methods such as GET, POST, PUT, PATCH, and DELETE.
-
Web routes are defined in
routes/web.php. -
API routes are defined in
routes/api.php. - Routes can accept parameters from the URL.
- Routes can be protected using middleware.
- Routes can be named, making URL generation easier.
- Routes can be grouped to share middleware, prefixes, or namespaces.
Example
Basic Route
Route::get('/about', function () {
return 'About Page';
});
Route Using a Controller
Route::get('/users', [UserController::class, 'index']);
Route with Parameter
Route::get('/posts/{id}', function ($id) {
return $id;
});