I am trying to orderBy()
my query based on if a field is NULL or not.
So, if minute
field is null, I want to orderBy id
; otherwise I want to use couple of different set of orderBy.
This shows the "minute not NULL" scenario:
public function events() {
return $this->hasMany(Event::class)
->orderBy('minute', 'desc')
->orderByRaw('type = ? desc', 'period')
->orderByDesc('external_event_id')
}
What I want to achieve is something like this pseudo code:
public function events() {
return $this->hasMany(Event::class)
->when('minute is NULL', function($q) {
$q->orderByDesc('id');
})
->when('minute is NOT NULL', function($q) {
$q->orderBy('minute', 'desc')
->orderByRaw('type = ? desc', 'period')
->orderByDesc('external_event_id');
});
}
Is there a way to achieve this using Laravel query builder?