Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get average of column values in laravel

Tags:

Lets say I have this column

star
----
1    
3    
3    
1    
2    
5    
3

It has seven rows and there are integer values! I want to have it added and divided by the rows there are.

How do I do it in laravel. I can do it in plain php but I want to learn it in laravel.

like image 663
Alen Avatar asked Mar 01 '17 10:03

Alen


Video Answer


2 Answers

Try this :

$avgStar = Model::avg('star');

" Model " will replace with your model name

like image 171
Muthu17 Avatar answered Sep 21 '22 09:09

Muthu17


If you want to do it with the query builder you can use aggregate methods like avg:

$avg_stars = DB::table('your_table')
                ->avg('star');

Laravel 5 docs about aggregates.

like image 37
Troyer Avatar answered Sep 19 '22 09:09

Troyer