25

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.

Alen
  • 1,221
  • 5
  • 21
  • 43

6 Answers6

55

Try this :

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

" Model " will replace with your model name

Muthu17
  • 1,481
  • 12
  • 20
13

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.

Troyer
  • 6,765
  • 3
  • 34
  • 62
4

If you have more columns you can use the native function of the database manager using DB::raw

$products = DB::table('products')
                 ->select('id','name',DB::raw('round(AVG(quantity),0) as quantity'))
                 ->groupBy('id','name')
                 ->get();
Vladimir Salguero
  • 5,609
  • 3
  • 42
  • 47
0

Just try

$avgStar = yourModel::avg('columnName');

// in this case
$avgStar = yourModel::avg('star');

Try this if you need to add multiple conditions - with model:

$avgStar = YourModel::Where(
  [
    ['star', '>', 1],
    ['star', '<>', 0]
    .....
  ])->pluck('star')->avg();

With database:

 $avgStar = DB::table('table_name')->Where(
  [
    ['star', '>', 1],
    ['star', '<>', 0]
    .....
  ])->pluck('star')->avg();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
-1

Table::Where('column', $case)->pluck('column')->avg()

  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Dave Jan 14 '20 at 01:19
  • This will first load all `column` in memory, then loop through it and calculate avg, this is expensive, instead, let MySQL do it like mentioned above. – Adham shafik Sep 20 '22 at 10:00
-3

// let's say the Model name is Review and Table name is reviews, you have a 'star' column on it

$value = Reviews::all();
$value->avg('star');

return view('page.name')->withValue($value);

// it will calculate an average of star column

Chen Hill
  • 3
  • 1