Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How do I create a custom pivot model?

I'm working on a project that has a many to many relationship between User and Club. This relationship works and I can get the respective objects with: $user->clubs. The pivot table I've named memberships. I can get the pivot data with $club->pivot. Foreign keys are defined for the memberships table in migrations.

However, I'd like the pivot table to be represented by a model so that I can easily update attributes of Membership such as role (Or even add a Role model to Membership!) or status.

I've looked at "Defining A Custom Pivot Model" in the docs, but what it says doesn't work for me, I get:

ErrorException Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given

I've also looked at this description of how to do it, but it's more or less the same as above.

Membership model:

class Membership extends Eloquent {

protected $table = 'memberships';

public function user()
{
    return $this->belongsTo('User');
}

public function club()
{
    return $this->belongsTo('Club');
}
}

Has anyone done this before?

like image 531
Robin Avatar asked Jan 18 '14 11:01

Robin


2 Answers

This has been solved by a suggestion by a reddit user to extend Pivot in my Membership model. I also had to add ->withPivot('status', 'role')->withTimestamps() to the relationship declarations in the User and Club models.

like image 192
Robin Avatar answered Sep 28 '22 20:09

Robin


You can do this by adding some manual code.

Your Membership model looks ok. You can get all clubs of a $user easily if you define method $user->clubs() where you get all the clubs manually.

clubs() {
    $memberships=$this->memberships;
    $clubs=new \Illuminate\Database\Eloquent\Collection();
    foreach($memberships as $m) {
        $clubs=$clubs->merge($m->clubs);
    }
    return $clubs;
}
like image 32
Margus Pala Avatar answered Sep 28 '22 18:09

Margus Pala