This Laravel package enables dynamic eager loading and sorting in your API controllers.
You can install the package via composer:
composer require amsoell/withable-sortable
Add the withable()
and sortable()
calls on any Eloquent queries in your API controllers to automatically enable eager loading and sorting through querystring parameters. An controllerless example:
use Illuminate\Support\Facades\Route;
Route::get('/users', function () {
$users = User::query()
->sortable()
->withable();
return $users->paginate()->withQueryString();
});
/users
will return users sorted by the default (created_at
in ascending order)/users?sort=email
will return users sorted by email address/users?sort=email&direction=desc
will return users sorted by email in descending order/users?with=posts
will return users with aposts
relationship eager loaded/users?with[]=posts&with[]=comments
will return users withposts
andcomments
relationships both eager loaded
If you want to specifically eager load some relationships while allowing additional eager loads via with=
, you can specify them in your route method:
$users = User::query()->withable([
'posts',
]);
You can also set the default sort parameters:
$users = User::query()->sortable([
'updated_at',
'asc',
]);
Even when setting default eager loads or sorts, they can be added to or overridden via querystring paramters.
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
This package was generated using the Laravel Package Boilerplate.