Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

floflo's avatar

Convert MySQL query in Eloquent query.

Hi all,

I'm trying to convert a MySQL query to an Eloquent query but I can't find the right answer.

select number,DATE(start),sum(duration),count(*),SUM(if(duration = 0, 1, 0)) AS comments from histories group by number,DATE(start);

Really appreciate any ideas.

0 likes
2 replies
lostdreamer_nl's avatar
Level 53

I think this should work:

$result = \DB::table('histories')
 ->selectRaw('number, DATE(start), sum(duration), count(*), SUM(if(duration = 0, 1, 0)) AS comments')
 ->groupBy(\DB::raw('number, DATE(start)'));

dd($result);
1 like
Cronix's avatar

There's also really no benefit to using eloquent in that particular situation. As you see, it's almost entirely raw statements anyway. It would actually be faster to just use your original query as then php/laravel doesn't have to translate the eloquent query back to raw sql.

$query = 'select number,DATE(start),sum(duration),count(*),SUM(if(duration = 0, 1, 0)) AS comments from histories group by number,DATE(start)';

$result = \DB::unprepared($query);
1 like

Please or to participate in this conversation.