Using withAggregates in Eloquent way

Suppose Post hasMany Rating and there is a field rating in ratings table.

For this following snippet can be used to retrieve all posts with its rating count, average rating, maximum and minimum given rating

// In controller
$posts = Post::withCount('ratings')
	->withAvg('ratings', 'rating')
	->withMax('ratings', 'rating')
	->withMin('ratings', 'rating')
	->get();

// Then, In view rating count, avg rating, max rating and min rating 
// for posts loop can be accessed using post object

$post->ratings_count
number_format($post->ratings_avg_rating, 2)
$post->ratings_max_rating
$post->ratings_min_rating

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent