Reputation: 2381
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 like auth()->user()->products()->first()->pivot->contribution()
but it gives some error.
Call to undefined method Illuminate\Database\Eloquent\Relations\Pivot::contribution()
Upvotes: 0
Views: 2092
Reputation: 2381
Inspired by this problem. We cannot call function on pivot object.
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']);
}
Upvotes: 0
Reputation: 211
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.
Upvotes: 1