Ezrab_
Ezrab_

Reputation: 983

Laravel 7 multiple where clauses with sortBy

Can someone explain how to do this with laravel eloquent? I can't seem to find a solution online (note that all times are in unix timestamp):

$this->model
            ->sortBy('start_datetime') // is unix timestamp
            ->where('start_datetime', '>', now()->startOfWeek()->timestamp)
            ->where('end_datetime', '<', now()->endOfWeek()->timestamp)
            ->get();

This generates the following error: Call to undefined method App\Models\Model::sortBy()

I want to retrieve the datetimes in my database from the current week and then sort it by what day comes first. Because I'm using numbers (unix timestamp) in my db this shouldn't be so hard I guess.

P.S. I don't want to use Facades or static methods for this issue. So no answers with Model::

Upvotes: 0

Views: 307

Answers (2)

Spholt
Spholt

Reputation: 4032

The error you are getting is because you are trying to use a Collection method on an Query Builder instance, hense it's an undefined method error.

Try changing the order of your chained methods and use orderBy() rather than sortBy():

$this->model
            ->where('start_datetime', '>', now()->startOfWeek()->timestamp)
            ->where('end_datetime', '<', now()->endOfWeek()->timestamp)
            ->orderBy('start_datetime') // is unix timestamp
            ->get();

Addendum - sortBy() vs orderBy

sortBy() is a method on both Eloquent & Support Collection classes and can be considered some sugar on top of a PHP asort() or arsort().

orderBy() is a method on a QueryBuilder class and is essentially adding the following to your database query (if using SQL)

ORDER BY `start_datetime`;

They can both produce the same output but in different ways. One is before the query is run and the other applies to the query results.

Upvotes: 1

Lukas
Lukas

Reputation: 1123

Refering to Laravel Docs: The sortBy() method sorts the collection by the given key. The sorted collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes.

So you need to call sortBy() on the collection delivered through get():

 $data =    $this->model
            ->where('start_datetime', '>', now()->startOfWeek()->timestamp)
            ->where('end_datetime', '<', now()->endOfWeek()->timestamp)
            ->get()->sortBy('start_datetime');

Upvotes: 0

Related Questions