Routing
Basic Routing
Routes map URLs to handlers. Define them in routes/web.php:
php
$app->get('/', function () {
return 'Hello, World!';
});
$app->post('/users', function () {
return 'Create user';
});Available Methods
php
$app->get('/path', $handler);
$app->post('/path', $handler);
$app->put('/path', $handler);
$app->patch('/path', $handler);
$app->delete('/path', $handler);Route Parameters
Capture dynamic segments with {parameter}:
php
$app->get('/users/{id}', function (string $id) {
return "User: {$id}";
});
$app->get('/posts/{post}/comments/{comment}', function (string $post, string $comment) {
return "Post {$post}, Comment {$comment}";
});Parameters are automatically injected into your handler.
Controller Routes
Point routes to controller methods:
php
use App\Controllers\UserController;
// Array syntax
$app->get('/users', [UserController::class, 'index']);
$app->get('/users/{id}', [UserController::class, 'show']);
// String syntax
$app->get('/users', 'App\Controllers\UserController@index');Named Routes
Give routes a name for URL generation:
php
$app->get('/users/{id}', [UserController::class, 'show'])->name('users.show');Generate URLs:
php
$url = $app->url('users.show', ['id' => 123]);
// /users/123Route Groups
Group routes with a common prefix:
php
$app->group('/api', function ($router) {
$router->get('/users', [ApiUserController::class, 'index']);
$router->get('/posts', [ApiPostController::class, 'index']);
});
// Results in:
// GET /api/users
// GET /api/postsGroups can be nested:
php
$app->group('/api', function ($router) {
$router->group('/v1', function ($router) {
$router->get('/users', [V1UserController::class, 'index']);
});
});
// GET /api/v1/usersRoute Handlers
Routes accept several handler types:
Closures
php
$app->get('/', function () {
return 'Hello!';
});Controller Methods
php
$app->get('/', [HomeController::class, 'index']);Invokable Controllers
php
$app->get('/', HomeController::class);The controller must have an __invoke method.
Accessing the Request
Handlers receive the PSR-7 request:
php
use Psr\Http\Message\ServerRequestInterface;
$app->post('/users', function (ServerRequestInterface $request) {
$data = $request->getParsedBody();
return "Creating: {$data['name']}";
});