Laravel Carbon::today() method return previous day

时间:2018-09-18 20:24:59

标签: php laravel laravel-5 php-carbon

I have written a function to filter user and agent booked tickets based on date. This is basically an ticket booking application. In this user and agent can book different tickets, so in admin dashboard I am displaying the count of total number of tickets booked by user by today and vice versa for agents. Thus I do this using Carbon to verify with today date. But I am getting different kind of output !

Controller :

$ticketsTodayUsers = Booking::with('users')->where("createdAt", ">=", Carbon::today())->whereHas("users", function($subQuery){ 
    $subQuery->where("usertype", "=", "normal");
    })->get();

So in this I have two tables, booking and user table by which I am verifying tickets created today using carbon::today() with usertype as normal or agent.

But when I check today (19-sep-2018), I am getting counting result of yesterday (18-sep-2018 ). I am not getting the count of today, which is zero instead the count comes from yesterday or long back like 14-sep-2018. I don't know where I am doing wrong !

The main condition is that I need to separate user and agent bookings counts for each day , so by using createdAt filed from db and carbon today function I tried to match both. But I am not getting expected answer !

3 个答案:

答案 0 :(得分:0)

Try to use $tz parameter - TimeZone.

Carbon::today('Asia/Calcutta');

And try to use WhereData(), WhereDay():

->whereDay('createdAt', '=', date('d'))

or

->whereDate('createdAt', Carbon::today())

Of course with appropriate timezone

Booking::with('users')->whereDate('createdAt', Carbon::today('Asia/Calcutta')->toDateString())->whereHas("users", function($subQuery){
            $subQuery->where("usertype", "=", "normal");
        })->get();

答案 1 :(得分:0)

尝试一下:

$ticketsTodayUsers = Booking::with('users')
     ->whereDate("createdAt", ">=", Carbon::now()->toDateString())
     ->whereHas("users", function($subQuery){ 
         $subQuery->where("usertype", "=", "normal");
     })->get();

答案 2 :(得分:0)

这对我有帮助

$ticketsTodayUsers = Booking::with('users')->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->addHour()])->get();