What do you mean with "create an own custom attribute"?
Normally you may use the query builder orderBy() method with Eloquent models too, or at least the Collection sortBy().
I mean that if I for example create something like this in my model:
public function getCountAttribute()
{
return $this->someNumber +
OtherModel::where('something', $this->id)->pluck('someNumber');
}
I can then reach that value by $model->count, but can I somehow order by that attribute?
Your example leads to sorting the collection at application level, but that may perform poorly without eager loading.
So, first try to define a proper Eloquent relation and simplify your accessor, e.g.
class SomeModel extends Eloquent {
...
public function getCountAttribute()
{
return $this->someNumber + $this->relatedModel->someNumber;
}
...
}
At that point, you could try something like this:
$orderedModels = SomeModel::with('relatedModel')->get()->sortBy('count');
This may need some tuning but I hope it points you in a good direction.
Yeah, I will not use what I had in my example, it was just a quickly put together example to show what I wanted to achieve.
I was not aware of the sortBy method, that's exactly what I am looking for. Thank you very much.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community