Abdul
Abdul

Reputation: 1607

Carbon and Eloquent times

I am trying to display all the entries entered within a specific time, from 27-02-2018 22:00:00 to 28-02-2018 05:59:59, here is what I got so far, but i am not getting any results back from the webpage

$NightStart='22:00:00';
$NightEnd='05:59:59';
$dcmlogs = log::with('users')->whereBetween('created_at',['Carbon::today()->toDateString() $NightStart','Carbon::yesterday()->toDateString() $NightEnd'])->paginate(10);

Why I am not getting any results? I am sure there are some rows with these timestamps in the database.

Upvotes: 0

Views: 196

Answers (3)

HelloSpeakman
HelloSpeakman

Reputation: 830

If you wish to do this entirely with Carbon you can use the following:

$dcmlogs = log::with('users')->whereBetween('created_at',[
    Carbon::yesterday()->hour(5)->minute(59)->second(59)->toDateTimeString(),
    Carbon::today()->hour(22)->toDateTimeString()
])->paginate(10);

Alternatively you can also use setTime($h, $m, $s) instead of manually setting conditions

$dcmlogs = log::with('users')->whereBetween('created_at',[
    Carbon::yesterday()->setTime(5, 59, 59)->toDateTimeString(),
    Carbon::today()->setTime(22, 0, 0)->toDateTimeString()
])->paginate(10);

Your example you were using single quotations which parses your conditions as a string and also wasn't appending properly.

Upvotes: 0

Imran
Imran

Reputation: 4750

Try changing this line:

$dcmlogs = log::with('users')->whereBetween('created_at',['Carbon::today()->toDateString() $NightStart','Carbon::yesterday()->toDateString() $NightEnd'])->paginate(10);

To:

$fromTime = Carbon::yesterday()->toDateString()." $NightEnd";
$toTime = Carbon::today()->toDateString()." $NightStart";

$dcmlogs = log::with('users')
    ->whereBetween('created_at', [$fromTime, $toTime])
    ->paginate(10);

Upvotes: 0

Claudio
Claudio

Reputation: 5203

Php doesn't parse values inside ' only inside ":

Try:

$NightStart = '22:00:00';
$NightEnd = '05:59:59';
$today = Carbon::today()->toDateString() . ' ' . $NightStart;
$yesterday = Carbon::yesterday()->toDateString() . ' ' . $NightEnd;
$dcmlogs = log::with('users')->whereBetween('created_at',[$yesterday, $today])->paginate(10);

Upvotes: 2

Related Questions