You have at three ways you can do this:
- A) You can apply it to all queries.
- B) Or you can create single scope in your model and call it on the query.
- C) Or you can sort by however you directly on your query
A) You can apply it to all queries with:
- Create a new scope file locate at
/app/Scopes/SortByScope.php
Then that file (SortByScope.ph
p) should look like:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class SortByScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->orderBy('MyAttribute', 'DESC');
}
}
- In your model include the call in your head
<?php
namespace App;
use App\Scopes\SortedOrderScope;
...rest of your model...
- Include the folling in your Model:
/**
* Apply to all queries.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::addGlobalScope(new SortByScope);
}
https://laravel.com/docs/master/eloquent#global-scopes
B) Or you can create single scope in your model and call it on the query with:
- In your model input the folling method:
/**
* Scope a query to be sorted by MyAttribute
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSortedByMyAttribute($query)
{
$builder->orderBy('MyAttribute', 'DESC');
}
- Then in your Query use it with:
$results = App\MyModel::sortedByMyAttribute()->get();
-or-
$results = App\MyModel::where('foo', '=', 'bar')->sortedByMyAttribute();
https://laravel.com/docs/master/eloquent#local-scopes
C) Or you can sort by however you directly on your query with:
$results = App\MyModel::orderBy('MyAttribute', 'DESC')->get();