Jim Reynolds
Jim Reynolds

Reputation: 21

How to orderBy Laravel Mutator value

I am trying to use a Laravel Mutator date value in an orderBy clause but getting an 'unknown column' error.

I have an Appointment model with client_uid and sched_start among many other data elements. sched_start is a datetime.

I have added a protected $appends array:

protected $appends = ['dayofweek', 'startdateformat',  'startendformat', 'endformat' ...]

...
public function getStartdateformatAttribute(){
    return $this->sched_start->format('Y-m-d');
}    

In the code, I can access the protected $appends elements. For example

Log::error($appointments->first()->startdateformat);

logs the value as expected. However, I want to use that in an orderBy clause:

$appointments->orderBy('startdateformat', 'ASC')->orderBy('client_uid', 'ASC')->orderBy('sched_start', 'ASC');

When I do that, however, I get an error:

Column not found: 1054 Unknown column 'startdateformat' in 'order clause'' in C:\wamp64\www\dev ...

How can I access the startdateformat value in the $appends array in the orderBy clause?

Upvotes: 0

Views: 586

Answers (1)

Elias Soares
Elias Soares

Reputation: 10264

You can't order by that column since it doesn't exists on database.

Since your mutator just formats the date field, you can just order by the original column:

$appointments->orderBy('sched_start')

Should work just fine.

If sometime you really need to order by a mutator, you will need to do it on collection instead of on database:

$appointments->get()->orderBy('mutator_column')

Note that this will not work as expected with pagination (it will order only the current page, not the entire table) and is not efficient with large dataset.

Upvotes: 1

Related Questions