简体   繁体   中英

How to check current date record in laravel?

I am trying to check game_id only for today or current date and for this I am trying following script

$todayExist = Training::whereRaw("Date(created_at)=Curdate() and game_id=$game_id")->get();
        if($todayExist->count() > 0 ){
            $error = 1;
            $result = false;
        } 

The above query output is

select * from `games_training` where Date(created_at)=Curdate() and game_id=6

But for game_id=6 there is duplicate entry, as it was generated by 3 hours ago (Dubai Time).

So can someone kindly guide me what can be the issue? Is it wrong query or it happened because server timezone.

I just insert record, in server database it is showing 09:31:57 which mean is 09:31 AM, however I am in Dubai and right now here is 1:33 PM.

Can someone kindly guide me about it.

Thank you so much.

Go to

config -> app.php and change 'timezone' => 'Asia/Dubai'

. Then

php artisan config:cache

您可以在“ config-> app.php”中找到时区配置,只需将'timezone' => 'UTC', to 'timezone' => 'Asia/Dubai',更改'timezone' => 'UTC', to 'timezone' => 'Asia/Dubai',然后重新启动XAMPP。

The current date means what for you? Because you have the mysql server timezone, your lavarel timezone setting and your computer's timezone setting ... When you write: Date (created_at) = Curdate (), Curdate () examines the time zone of the mysql server. So what is the "current date" you want to find ? Remember that every user in the world has their own "current local date" while the date stored in your mysql database will only be a fixed date (it is better to be UTC for more reliability ... )

Laravel 5.6+ users, you can just do

$posts = Post::whereDate('created_at', Carbon::today())->get();

Besides now() and today() , you can also use yesterday() and tomorrow() and then use the following:

startOfDay()/endOfDay()
startOfWeek()/endOfWeek()
startOfMonth()/endOfMonth()
startOfYear()/endOfYear()
startOfDecade()/endOfDecade()
startOfCentury()/endOfCentury()

OR

Using query builder,Use Mysql default CURDATE function to get all the records of the day.

 $records = DB::table('users')->select(DB::raw('*'))
                  ->whereRaw('Date(created_at) = CURDATE()')->get();
    dd($record);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM