-1

I'm making a feedback stars rating system for products using Laravel with MySQL, how can I make MySQL count all rates and get the average of 5 stars?

So by laravel I am going to just use get() to get the average.

//sample data:

id | rate
1     4
2     2

//expected output:

3
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Wail Hayaly
  • 1,057
  • 1
  • 15
  • 31

2 Answers2

1

In order to answer more precisely, the structure of the table should be known. You can group the desired lines and then divide by the number. something like this:

SELECT SUM(rate)/COUNT(1) FROM table GROUP BY 1

or with AVG function

SELECT AVG(rate) AS avgRate
FROM table
GROUP BY xyz;

see https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_avg

DB::table('your_table')
                ->avg('star');
0

You can do something like this,

$rateAvg = Model::avg('rate');

Check this links for more

How to get average of column values in laravel

Aggregates in laravel

Maulik Shah
  • 1,040
  • 1
  • 7
  • 17