I have following Eloquent model:
class Song extends Eloquent {
protected $table = \'mg_songs\';
protected $hidden = array(\'events\');
protected $appends =
You can sort the resulting collection by accessor, obviously the query can't be ordered, for it's not in the db.
$songs = Song::all(); // get the result
$songs->sortByDesc('lastDate'); // sort using collection method
// or ascending:
$songs->sortBy('lastDate');
You could achieve the same using joins
, if you prefer to do this in the db call (it's better in terms of performance).
Another thing: you use if( ! $this->events)
which will cause trouble soon.
Check this out:
// hasOne / belongsTo / morphTo etc - single relations
$model->relation; // returns related model OR null -> evaluates to false
// BUT for hasMany / belongsToMany etc - multiple results
$model->relation; // always returns a collection, even if empty, evaluates to true
So change this if
to:
public function getLastDateAttribute()
{
if ( ! count($this->events)) return null;
return $this->events[0]->date->formatLocalized('%d.%m.%Y (%a, %Hч)');
}}