Implement routing in Leaf PHP v5
Routing differs by project type. In Basic apps, routes go in index.php. In MVC apps, routes are placed in app/routes/ as partials (files starting with _, e.g., _posts.php), which are automatically loaded.
Routing Rules:
- Use the array format
['key' => 'value', ..., handler]only when specifying middleware, names, or module keys. The handler (closure orController@method) must always be the last element. - In MVC apps, never call
app()->run(); the framework handles this automatically. - Always return responses (e.g.,
return response()->json(...)).
// Basic routes
app()->get('/home', fn () => response()->json(['status' => 'ok']));
app()->put('/users/{id}', function ($id) { /* ... */ });
// MVC: Controller routing
app()->get('/posts', 'PostsController@index');
// Routes with middleware or names
app()->get('/dashboard', ['middleware' => 'auth.required', 'DashController@index']);
app()->get('/home', ['name' => 'home', function () { /* ... */ }]);
// Groups and Named Groups
app()->group('/admin', ['name' => 'admin', 'middleware' => 'auth.required', function () {
app()->get('/dashboard', ['name' => 'dashboard', 'AdminController@dashboard']); // Route name: admin.dashboard
}]);
// Resource routes
app()->resource('/photos', 'PhotosController');
// Generating URLs from names
app()->route('admin.users.show', ['id' => 5]);