Polymorphic relationship Laravel

Posted: 2014-07-20 13:15:54

This example will show a typical "Attachment" need. The Laravel docs really do cover alot as seen here especially "Polymorphic Relation Table Structure”. I cover many to many polymorphic relationships here

I will cover an example of an Attachment that has some fields. And it is related to a model, in this example "Post"

Using the Way Generators to make this resource.

php artisan generate:resource attachment --fields="attachable_type:string, attachable_id:integer, name:string, file_name:string, note:text, tag:string”

As noted in the laravel docs our table for Attachments would look something like this

post
    id - integer
    name - string
    body - text

attachments
    id - integer
    file_name - string
    attachable_id - integer
    attachable_type - string

So we are making a table/model Attachment. The model will use the "attachable" syntax to dynamically reference another model and model id.

In the Post model I set that this relationship exists

#app/models/Post.php
 public function attachments()
    {
        return $this->morphTo("Attachment", "attachable");
    }

The Attachment model file is this


<?php #app/models/Attachment.php class Attachment extends \Eloquent { protected $fillable = [ "attachable_type", "attachable_id", "name”, “file_name”, "note", "tag" ]; public function attachable() { return $this->morphTo(); } }

Finally if we where to seed the db or add content the table for Attachments would look like this

example

the attachable_type is the model class so if the namespace was Acme\Post then that would be "Acme\Post

That is it. As long as you include it in your results you will see it in your output.