Jerad
Jerad

Reputation: 211

How to get the average time in Laravel

I want get the the average time between start-time and end-time and Where CUR-Time GroupBY user-name i written the sql in laravel it's showing some error i can't find what's that because i'm new to that laravel please help to fix this sql error i submit the my sql and the error message.

 $avagTime = DB::table( 'active_user' )
            ->select(DB::raw('AVG(TIME_TO_SEC(acu_et) - TIME_TO_SEC(acu_at))'))
            ->where (DATE('acu_at') == ('CURDATE()'))
            ->get();[![enter image description here][1]][1]

enter image description here

enter image description hereenter image description here

Upvotes: 2

Views: 2456

Answers (3)

Rwd
Rwd

Reputation: 35210

The issue is in your where clause. Laravel's query builder has a whereDate() method that would be perfect for this:

$avagTime = DB::table('active_user')
    ->selectRaw('AVG(TIME_TO_SEC(acu_et) - TIME_TO_SEC(acu_at))')
    ->whereDate('acu_at', today())
    ->get();

NB If you wanted to pass the where cause as a raw query (like you have in your example) you would need to use something like whereRaw() instead or where().

Upvotes: 1

Amir Hedieh
Amir Hedieh

Reputation: 1178

Isn't it better to take the logic out of there? I prefer to just fetch date times from DB and using Carbon to convert them to Unix timestamp. Then use them as they are simple int.

Upvotes: 0

Inzamam Idrees
Inzamam Idrees

Reputation: 1981

Try this code:

$currentTime = Carbon::now()->toDateTimeString();

$avagTime = DB::table( 'active_user' )
          ->select(DB::raw('AVG(TIME_TO_SEC(acu_et) - TIME_TO_SEC(acu_at))'))
          ->where ('acu_at', $currentTime)
          ->get();

I think it would be helful. Thanks

Upvotes: 0

Related Questions