Laravel’s Eloquent offers a variety of features to retrieve, store and update data. Interestingly it can also aggregate and calculate things like sums, maximum or averages. In this post we learn how to aggregate data with Eloquent along with a calculated average. You Can Learn How to Implement Email Verification in Laravel?
How to Calculate the Average of a Column Using Eloquent we can do 2 things:
// Method 1: Get the average rating of all movies combined (single model)
$avgStar = Rating::avg('rating');
// Method 2: Use `withAvg` to get each movie and its average rating (using relationship)
$movies = Movie::select()
->withAvg('ratings', 'rating')
->get();
In this post we will create an application where users browse a movie database and views their average ratings. For this, we will use the withAvg method to calculate the average, and read the resulting value from the ratings_avg_rating attribute (following Laravel’s naming convention).
We will render the results using a Blade view with a user-friendly table.
Let’s get started! How to Calculate the Average of a Column Using Eloquent
Step 1: Create a Laravel Project
Start by creating a new Laravel project by running:
composer create-project laravel/laravel movie-rating-app
cd movie-rating-app
Related: '
Laravel 11 Custom Forgot Password Tutorial