php - Laravel PIVOT table with extra fields

one text

Solution:

I would suggest to perform a separate single query for products that belongs to user via license as

$products = Product::whereHas('licenses.user', function (Builder $query) use($user) {
                       $query->where('id', $user->id);
                     })->paginate(5);

or

$products = Product::whereHas('licenses', function (Builder $query) use($user) {
                       $query->where('user_id', $user->id);
                     })->paginate(5);

This way you don't have to loop through all data to extract products from lazy loaded relation and no need for unique action also

Source