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

iamssingh's avatar

How to use truncate & avg function in laravel query ?

SELECT TRUNCATE(AVG(rating),2) FROM `reviews` WHERE restro_id=9

I want to write above query in laravel, How can I achieve it ?

0 likes
3 replies
Tray2's avatar
Tray2
Best Answer
Level 73

You can use something like

DB::table('reviews')
	->select(DB:raw('TRUNCATE(AVG(rating),2)')
   ->where('restro_id', 9)
  ->get()
1 like
s4muel's avatar

or select the rating using avg aggregation method available in query builder and format it using php (instead of sql truncate)

$rating = number_format(DB::table('reviews')->where('restro_id', 9)->avg('rating'), 2);
1 like
iamssingh's avatar

@tray2 @s4muel Thank you for quick response guys. I did it like this as suggested by @tray2 -

\App\Models\Review::select(\DB::raw('TRUNCATE(AVG(rating),2) as rating'))
        ->where('restro_id',$id)
        ->get();

Please or to participate in this conversation.