A simple trait to make your Laravel Eloquent models sortable with ease.
Using Composer:
composer require firevel/sortable
-
Import the
Sortable
trait in your Eloquent model. -
Add a protected
$sortable
array property to your model. This array should list the fields you want to allow for sorting.
use Firevel\Sortable\Sortable;
class User extends Model {
use Sortable;
/**
* Fields allowed for sorting.
*
* @var array
*/
protected $sortable = ['id', 'name', 'email'];
}
You can now easily sort your models using the sort()
query scope.
To sort by name
in ascending order:
User::sort(['name'])->get();
To sort by id
in descending order:
User::sort(['-id'])->get();
The -
sign before the field name indicates descending order.