Laravel select count in select Laravel select count in select laravel laravel

Laravel select count in select


You should use selectRaw() instead of select() and separate other parts of query to related methods:

$pois = DB::select(DB:raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps"))    ->from('pois')    ->orderBy('nbr_stamps', 'DESC')    ->limit(3);

Read the Query Builder documentation.


@thanks to limonte for the documentation link, i found the right way to write to select raw, here the solutions :

$pois = DB::table('pois')        ->select(DB::raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps"))        ->orderBy('nbr_stamps', 'DESC')        ->take(3)        ->get();

have a nice day ;)