Search code examples
laraveleloquentwhere-clause

fetch first daily row using Laravel Eloquent


i have a table called sans that stores event information with columns for id, date, and hour.
I'm trying to write a query using Eloquent to fetch the first event of each day. My current code works fine for today's events, but I'm having trouble modifying it to fetch the first event for each day beyond today. Can you help me with this?
my current code:

$sans=sans::where('id',$id)
->where('user_id',$user->id)
->whereDate('date','>=',date('Y-m-d'))
->where('Hour','>=',date('H:i'))
->first();

but its work correct just for today's sans


Solution

  • you can concate date and time use where condition & you can use DATE_FORMAT() link

    $sans=sans::where('id',$id)
             ->where('user_id',$user->id)
            ->where(DB::Raw("CONCAT(DATE_FORMAT(date,'%Y-%m-%d'),' ',hour)"),'>=',date('Y-m-d H:i'))
             ->orderBy('date','DESC')
             ->first();