Framework: Cannot use custom pivot models with polymorphic many to many relations

Created on 7 Sep 2017  路  8Comments  路  Source: laravel/framework

  • Laravel Version: 5.4
  • PHP Version: 7

Description:

I'm getting a call to undefined method error when trying use a custom pivot with a polymorphic many to many relationship.

Steps To Reproduce:

I setup a morph to many relationship on my page model like so:

class Page extends Model
{
    public function media()
    {
        return $this->morphToMany(Media::class, 'mediable')->using(MediaPivot::class);
    }
}

Now when I try and retrieve media from the page, i.e:

$media = $page->media()->get();

I get the following error:

Call to undefined method Illuminate\Database\Query\Builder::setMorphType()

Most helpful comment

your MediaPivot should extend MorphPivot instead of Pivot

All 8 comments

your MediaPivot should extend MorphPivot instead of Pivot

My mistake, thank you @roennow

Is this in the docs anywhere? @roennow

It should be documented, I had the same problem.

@roennow is this functionality available at all in 5.1?

@dtturcotte The class has existed since 4.1 so I would guess so. I haven't worked with a 5.1 in a long time but try it :)

Laravel Documentation, which is otherwise excellent, is missing such nuances, forcing us to probe SO and Github Issues for pointers. This is especially true in the case of advanced polymorphic relation concepts. These should ideally part of the documentation, as right now, someone who knows the internals of Laravel can only act as the knowledge base for the rest of us.

@thinkdj you can always help by sending prs to the docs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CupOfTea696 picture CupOfTea696  路  3Comments

felixsanz picture felixsanz  路  3Comments

ghost picture ghost  路  3Comments

shopblocks picture shopblocks  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments