0

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::

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you elaborate why I would use orderBy instead of sortBy ?
Sure. I've updated my answer with a explaination of sortBy() vs orderBy(). Both are viable but i would suggest doing your ordering in the query builder as it can be much more efficient.
0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.