Reputation: 65
I have a problem with Laravel 5 and Eloquent, when i compare dates with a where clause on a model i have, called Callback, i get 0 rows returned. If i do it with \DB:: instead, i get the correct rows returned.
$callbacks = Auth::user()
->callbacks
->where('datetime', '>', '0000-00-00 00:00:00')
->sortBy('datetime')
->values()
->take(10);
$callbacks2 = \DB::table('callbacks')
->where('datetime', '>', Carbon::today())
->get();
The only difference i can see is that the first one, is done through an Eloquent Relationship, which returns a Laravel Collection of all callbacks for the authenticated user.
If i remove the where
clause in the $callbacks
expression, it returns all callbacks, ( old as new ofcourse, as there are no filtering being done then).
I have tried with Carbon\Carbon::today()
instead of the string literal i have pasted above, it gives same result, and the datetime in the database for one of the callbacks is 2016-04-05 15:30:00
.
I have been frantically googling and trying all i could think of, and i really don't want to have to do a full extract of callbacks for a user, just to remove most of them in PHP before sending the ones for the day, to the view.
I know that i need to do another Where to avoid getting rows from the day after the day i'm looking for, I was just removing most of the chaining to clean it up :)
Any suggestions are very much welcome!
Upvotes: 0
Views: 314
Reputation: 33068
As Okneloper indicated, as soon as you use ->callbacks
, a collection is returned. The trick is to keep this as a builder until you are finished with the query.
$callbacks = Auth::user()->callbacks()->where('datetime', '>', '0000-00-00 00:00:00')->orderBy('datetime')->take(10)->get();
Please note you also need to change sortBy
to orderBy
which is the correct method to sort on the Builder
class.
Upvotes: 1
Reputation: 1283
Auth::user()->callbacks
is a collection, so you are calling where on the set of items in the collection. So the answer depends on the data you have in DB, but these will not produce same query.
I would assume the rows returned by DB::
are not realted to the current user.
You can see what queries have been run by calling
DB::enableQueryLog() // before the queried
dd(DB::getQueryLog() // after the queries have been run
Upvotes: 2