Felix Maxime Felix Maxime - 27 days ago 12
PHP Question

Converting Query Builder to Eloquent in Laravel

I have a user table, and a review table.

In my review table, there's a "star_rating" column.

I can get the average "star_rating" score for a user with the following query:

$star_rating = Review::where('artist_id', $user->id)->avg('star_rating');

However, this doesn't work too well when I'm printing out a bunch of users in blade (I want to show their average star_rating next to their names).

That's why I'd like to have a function in my
model that I can call to get a user's average star rating.

public function getAvgStarRating() {
return $this-> // logic goes here //;

Answer Source

Add this relation in your User model:

public function reviews()
    return $this->hasMany(Review::class, 'artist_id', 'id');

Then add this method to get average of star ratings

public function getAvgStarRating()
    return $this->reivews->avg('star_rating');

And if you need to display a group of user's rating, first eager load their reviews (it is more efficient)

$users = User::with('reviews')->get();


foreach($users as $user) {