How to get average of column values in laravel

✔ Recommended Answer

Try this :

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

" Model " will replace with your model name

Source: stackoverflow.com

Answered By: Muthu17

Method #2

To get the average of column values in Laravel, you can use the avg method provided by Laravel's Query Builder. Here's an example code snippet that demonstrates how to get the average of column values from a database table:

css
$average = DB::table('table_name')->avg('column_name');

In this example, replace table_name with the name of your database table and column_name with the name of the column you want to get the average for. The avg method will return the average value of the specified column.

You can also add additional conditions to your query using the where method. For example, to get the average of column values where a specific column meets a certain condition, you can do the following:

css
$average = DB::table('table_name')->where('other_column', '=', 'condition')->avg('column_name');

In this example, replace other_column with the name of the column you want to add a condition for and condition with the specific value you are searching for. The where method will filter the results to only include rows where the specified condition is true before calculating the average of the specified column.

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755