How to Get Average of a Column in Laravel?

November 26, 2022
Laravel
How to Get Average of a Column in Laravel?

In this post, you will learn how to get the average of the column in laravel.

It’s easy to get the average of a column in laravel but must know how to use the laravel eloquent.

Lets get started!

Method 1: Get Average using Model

In this method we are getting average of the column using model.

Syntax

ModelName::avg('column_name')

First we need to type Model Name first, then we need to type the eloquent avg in which we need to pass the column_name.

This will give us the average of the column name we mention.

Example

Let’s say we have reviews table in which we have the following columns:

  • rating
  • user_id

Now we need to calculate the average of rating where user_id will be 1.

Reviews::where('user_id',1)->avg('rating')

The above code will give us average rating where user_id is 1.

Method 2: Get Average using DB Class

In this method, we are calculating the average using DB Class.

Syntax

DB::table('table_name')->avg('column_name')

First we need to pass the table name to DB::table and then we need to pass the column_name to avg for taking average of column of the table.

Example

Lets again assume that we have reviews table in which we have following columns same as before:

  • rating
  • user_id

Lets now calculate the average for rating with the condition where user_id will be 1.

DB::table('reviews')->where('user_id',1)->avg('rating')

First, we are passing the table name reviews to the DB::table class and then we are passing the avg the column name rating.

Conclusion:

So to calculate the average of the column in laravel, we need to use avg laravel eloquent function which explained thoroughly above in the article.

I hope it was helpful. Let me know in the comments if you have any questions.

See you in the next article.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon