php - Laravel Eloquent: My Pivot table has relation
Get the solution ↓↓↓Here some information about the table
User table
-id
-name
UserProduct table
-id
-user_id
-product_id
Product table
-id
-name
Contribution
-id
-user_product_id
-contribution
User Model
public function products()
{
return $this->belongsToMany('App\Product');
}
Product Model
public function users()
{
return $this->belongsToMany('App\User');
}
UserProduct Pivot Model
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserProduct extends Pivot
{
public function contribution()
{
return $this->hasMany('App\Contribution');
}
}
I try likeauth()->user()->products()->first()->pivot->contribution()
but it gives some error.
Call to undefined method Illuminate\Database\Eloquent\Relations\Pivot::contribution()
Answer
Solution:
could you maybe use custom pivot table model.
class UserProduct extends Pivot
{
public function contribution()
{
return $this->belongsTo('App\Contribution');
}
}
// User model
public function products()
{
return $this->belongsToMany('App\Product')->using('App\UserProduct');
}
Hope it helps you.
Answer
Solution:
Inspired by this problem. We cannot call function on pivot object.
The solution was :
First, add UserProduct to aliases so we can call it in blade.
config\app.php :
'aliases' => [
'UserProduct' => App\UserProduct::class,
],
Then, use find function then call the relation function
Blade :
@foreach ($product->users as $user)
@foreach (UserProduct::find($user->pivot->id)->contribution()->get() as $contribution)
// viewing contribution attribute
@endforeach
@endforeach
Don't forget to include pivot id
Product Model :
public function users()
{
return $this->belongsToMany('App\User')
->withPivot(['id']);
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: method illuminate\database\eloquent\collection::paginate does not exist.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.