Laravel Eloquent – Get most popular product from summaries

  database, eloquent, laravel, php

I am trying to fetch the most popular product of all my summaries. Preverable the name of the product that is the most common among all the summaries.

I have a Summaries table and a products table with a pivot table in between.

The relation is as follows:

Product model

public function summaries()
        return $this->belongsToMany(Summary::class, 'product_summary', 'summary_id','product_id');

Summary model

public function products()
        return $this->belongsToMany(Product::class, 'product_summary', 'summary_id','product_id');

So when let’s say of all summaries in the database, most of them have Product A as product. I would like to retrieve the name or object of Product A so I know which product is the most common.

I can’t seem to make it work. I tried stuff like

$product = Summary::query()
    ->with(array('products' => function($query) {


$top = Summary::select()->with('products')

But it just does not work. What am I doing wrong?

Source: Laravel

Leave a Reply