t0berius's avatar
Level 13

limit fields returned by belongsToMany() with paginate()

Is there a way how I can limit the fields, being returned from a relation of type belongsToMany()?

Assume this relation inside User model class

public function favouriteSellers()
{
    return $this->belongsToMany('App\Models\User', 'favourite_sellers', 'user_id', 'seller_id');
}

Using

$items =  $items = Auth::user()->favouriteSellers()
            ->select('favourite_sellers.user_id', 'users.name',
                'users.slug') // fields to retrieve
            ->join('seller_users', 'favourite_sellers.seller_id', '=',
                'seller_users.user_id') // Join with sellerUsers
            ->withCount([
				//some relations we count...
                'confirmedProducts',
            ])
            ->latest('pivot_created_at')->get();

returns the collection with fields as requested:

 #attributes: array:8 [▼

but when I change get() to paginate() ALL attributes of the User model are inlcuded:

  #attributes: array:34 [▼

My main questions are:

1.) Why did I need to write favourite_sellers.user_id instead of users.id? For other fields (!= id) it's not required?

2.) Why did paginate() cause laravel to load all attributes of the model even if I specified to load only defined attributes?

0 likes
5 replies
Snapey's avatar
  1. because you are not loading users table
t0berius's avatar
Level 13

@snapey any chance to limit the loaded fields, even when using paginate(), I know these are not "many" fields, but it might rise depending upon the amount of loaded models (FavouriteSellers).

Thunderson's avatar

i see what you want. you want getting user who are favorite sellers !! your are using a wrong way, but it is very simple.

User::select('id','name','slug')->has('favoriteSellers')-> ...->paginate()
// because a favorite seller is necessarily seller user first 
ubedthaheem's avatar

You also can select fields in the relation function


$items = Auth::user()->withCount('favoriteSellers'); // with count
$items = Auth::user()->select([ 'id', 'name' ]) // select only attributes
                ->with('favoriteSellers:id,user_id,anOtherColumnName'); // select only attributes from relation
        
$items->paginate($limit);
t0berius's avatar
Level 13

Solved it by using:

->paginate(10, [])

(it needs to be an empty array), can someone please explain why an EMPTY array is required for this to work?!

Please or to participate in this conversation.