Search code examples
phplaraveleloquenteager-loading

Laravel eager load model from a hasMany relationship


There are 3 tables:

users: id, name

compliments: id, name

users_compliments: id, compliment_id, user_id, complimentor_id

Here is my User model:

class User extends Model
    public function sent_compliments()  {  
        return 
            $this->belongsToMany(
            'Compliment', 
            'users_compliments', 
            'complimentor_id',
            'compliment_id'
         )->withPivot('user_id');
}

here is an example response if I run $user->sent_compliments()->get()

Illuminate\Database\Eloquent\Collection {
     all: [
       Compliment {
         id: 2,
         name: "You are smart",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {
           user_id: 6,
           id: 99,
         },
       },
       Compliment {
         id: 52,
         name: "You are funny",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {
           user_id: 42,
           id: 186,
         },
       },
     ],
   }

but here is the response I want (it includes the actual User model instead of just the user_id in the pivot)

Illuminate\Database\Eloquent\Collection {
     all: [
       Compliment {
         id: 2,
         name: "You are smart",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {
           user_id: 6,
           id: 99,
         },
         user {
             id: 6,
             name: "John"
         }
       },
       Compliment {
         id: 52,
         name: "You are funny",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {
           user_id: 42,
           id: 186,
         },
           user {
             id: 42,
             name: "Alex"
         }
       },
     ],
   }

Is there a way to get this data with an eloquent eager load (like using the With:: command ) instead of iterating through the pivot, collecting the user_ids and manually querying the User table?


Solution

  • You need to define pivot class and add relation belongsTo to pivot model for user_id

    User Model

    public function sent_compliments()  {  
        return 
            $this->belongsToMany(
            'Compliment', 
            'users_compliments', 
            'complimentor_id',
            'compliment_id'
         )->withPivot('user_id')->using('App\UserComplement');
    }
    

    Pivot model use Illuminate\Database\Eloquent\Relations\Pivot;

    class UserComplement extends Pivot {
        protected $table = 'users_compliments';
    
        public function user(){
            return $this->belongsTo('App\User', 'user_id');
        }
    }
    

    Feth data

    //if you have user instance already then
    $complements = $user->sent_compliments;
    
    //if you don't have fetched user yet then try this 
    $user = User::with('sent_compliments')->find($userId);
    $complements = $user->sent_compliments;
    
    foreach($complements as $complement){
        dd($complement);
        dd($complement->pivot->user);
    }
    

    For details check this Defining Custom Intermediate Table Models https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

    EDIT

    As @JonasStaudenmeir pointed, there is no way to eager load pivot user relationship. Here is another solution

    User Model

    public function sent_compliments()  {  
        return $this->hasMany(UserCompliment::class , 'complimentor_id');
    }
    

    UserComplement model

    class UserComplement extends Model {
        $table = 'users_compliments';
    
        public function complimentor()  {  
            return $this->belongsTo(User::class , 'complimentor_id');
        }
    
        public function complement()  {  
            return $this->belongsTo(Compliment::class , 'compliment_id');
        }
    
        public function user()  {  
            return $this->belongsTo(User::class , 'user_id');
        }
    }
    

    Fetch Data

    $user = User::with('sent_compliments','sent_compliments.complement', 'sent_compliments.user')->find($userId);
    $sentComplements = $user->sent_compliments;
    
    foreach($sentComplements as $sentComplement){
        dd($sentComplement->complement);
        dd($sentComplement->user);
    }
    

    Hope it may clear you