Back to readme |
---|
In this example, we'll create a sorter that sorts the users based on the amount of comments they have.
We use the Artisan command to create a sorter class.
php artisan sort-request:make UserCommentCount
This creates the App/Http/Sorters/UserCommentCountSorter
class.
Open the sorter class. You'll need to set-up two things.
You should return the available sorting directions in the getDirections
method. In this example we'll have two directions: most and least.
public function getDirections(): array
{
return ['most', 'least'];
}
This is the part where you write the actual logic behind your custom sorter. Sorting logic goes in the apply
method.
You have access to the following:
$request
current request being performed.$builder
the Eloquent query builder that you can use to sort.$direction
the direction currently being sorted on.
Consider the following example:
public function apply(Request $request, Builder $builder, $direction): Builder
{
$builder->withCount('comments');
if($direction == 'most')
$builder->orderBy('comments_count', 'desc');
else
$builder->orderBy('comments_count', 'asc');
return $builder;
}
Your sorter should be ready for use. Your Laravel form request should look something like this:
class GetUsersRequest extends FormRequest
{
use SortsViaRequest;
/**
* Get the rules that the request enforces.
*
* @return array
*/
function rules()
{
return array_merge([
// This is where your normal validation rules go
], $this->sortingRules());
}
/**
* Returns the columns that can be sorted on.
*
* @return array
*/
function getSortableColumns(): array
{
return [
'comment-count' => App\Http\Sorters\UserCommentCountSorter::class
];
}
}
.. and make sure to retrieve your models with the package's method in your controller, otherwise the results won't get sorted.
$users = User::sortViaRequest($request)->get();
All done! The following behavior is now enabled:
# Get the users sorted by the most comments
https://example.test/users?sort=comment-count(most)
# Get the users sorted by the least comments
https://example.test/users?sort=comment-count(least)
- You can use "normal" column sorting and custom sorters together:
The above example enables sorting on the custom "comment-count" sorter, and the model's name column.
function getSortableColumns(): array { return [ 'name', 'comment-count' => App\Http\Sorters\UserCommentCountSorter::class ]; }
https://example.test/users?sort=comment-count(least),name(asc)