Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Hirotaka's avatar

Polymorphic Relationship with pivot

Hi I am having problems with relation and database design.

There are three tables called

'articles' , 'users' , 'companies' and articles_authors as polymorphic pivot with one attribute each called id: I implements this models


class Article extends Model
{

    public function authors()
    {
        return $this->hasMany('App\Article_Authors','article_id');
    }
}

class Article_Authors extends Model
{

     public function authorable()
    {
        return $this->morphTo();
    }

    public function article(){
    return $this->belongsTo('App\Article');
    }
}


class User extends Model
{

    public function authors()
    {
        return $this->morphMany('App\Article', 'authorable');
    }
}


class Company extends Model
{

    public function authors()
    {
        return $this->morphMany('App\Article', 'authorable');
    }
}


and after call $article->authors i get


0   
id  1
record_id   2
authorable_id   1
authorable_type "App\User"
created_at  "2019-03-22 15:56:38"
updated_at  "2019-03-22 15:56:38"
1   
id  2
record_id   2
authorable_id   1
authorable_type "App\Company"
created_at  "2019-03-22 15:56:59"
updated_at  "2019-03-22 15:56:59"

how to call this models now :(

0 likes
5 replies
bobbybouwmann's avatar

Well you can just loop over the authors and call the authorable property to get them back. So something like this

foreach ($article->authors as $author) {
    $authorable = $author->authorable;
    
    if ($authorable instanceof \App\User::class) {
        // Here is your user
    }

    if ($authorable instanceof \App\Company::class) {
        // Here is your company
    }
}

Source: https://logrocket.com/blog/polymorphic-relationships-in-laravel/

1 like
Hirotaka's avatar

@BOBBYBOUWMANN - I had a similar idea but i'm not sure its good practice. there is a lot articles like i get 100 items per site i don't whant to make 1000 loops to display this. And will have problem later to inject this into api resource :(

bobbybouwmann's avatar
Level 88

@hirotaka Well yes, but that is one of the disadvantages of using a one-to-many polymorphic relationship.

If you would use a one-to-one polymorphic relationship you wouldn't have this issue, however that would mean an article can only have one author.

2 likes
Hirotaka's avatar

@BOBBYBOUWMANN - I think its more like many-to-many polymorphic, but i understand there is no hope for me. I will try this loop and cache result we will see how it's will works.

thanks for dispelling doubts.

Please or to participate in this conversation.