Coderz9
Coderz9

Reputation: 173

laravel pivot table return all related data

Pretty simple task actually but I've missed something, please give me a second pair of eyes to find my fault

Problem: Query returns only ONE row (should return 3)

//App\User.php
    public function languages() {
    return $this->belongsToMany(CustomLanguage::class,'custom_language_user','lang_id','user_id')->withPivot('lang_id','user_id');
}

//App\CustomLanguages.php
    public function users() {
    return $this->belongsToMany(User::class,'custom_language_user','user_id','lang_id')->withPivot('user_id','lang_id');
}

What i tried to query all languages for User x:

        $user = User::find(Auth::id());
        foreach($user->languages as $l) {
            Log::info($l);
        }


//Returns [2019-09-18 11:38:51] local.INFO: [{"id":1,"lang_de":"Deutsch","lang_en":"German","pivot":{"lang_id":1,"user_id":1}}]

even though , in my database i have: user_id :1 ,1 ,1 lang_id :1 , 2 , 3

so 3 rows i am kinda missin something, thanks in advance

Upvotes: 1

Views: 107

Answers (1)

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

you passed the wrong parameter in a relationship.

If you are in User.php model parameter should be.

return $this->belongsToMany(CustomLanguage::class,'custom_language_user','user_id','lang_id')->withPivot('lang_id','user_id');

If you are in CustomLanguages.php model parameter should be.

 return $this->belongsToMany(User::class,'custom_language_user','lang_id','user_id')->withPivot('lang_id','user_id');

So now you model looks like.

 //App\User.php
    public function languages() {
    return $this->belongsToMany(CustomLanguage::class,'custom_language_user','user_id','lang_id')->withPivot('lang_id','user_id');
}

//App\CustomLanguages.php
    public function users() {
    return $this->belongsToMany(User::class,'custom_language_user','lang_id','user_id')->withPivot('user_id','lang_id');
}

Upvotes: 1

Related Questions