Laravel default orderBy with one record always first
Hello, im looking for a way to solve my problem. I want to sort Role by it's name but keep specific one as first. For example if I have roles A, B, C, D i want to C be always first then others be ordered by name so the result would be C, A, B, D. And I want to keep this Role order in other models such as User
class Role extends Model
{
public static function booted()
{
static::addGlobalScope(
'default_ordering',
fn ($q) => $q->orderByRaw("name = 'C', name")
);
}
}
@tykus and how can i choose if its ASC or DESC? tried fn ($q) => $q->orderByRaw("(name = 'C', name) DESC") but it doesnt seem to work
//edit okay nvm, solved
@tykus yea, thanks a lot, but for some reason i had to write it this way fn ($q) => $q->orderByRaw("name, name = 'C") because otherwise it always was last