laravel 🚀
php 🚀
note2self 🚀
Polymorphic relationship Laravel

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

    id - integer
    name - string
    body - text

    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

 public function attachments()
        return $this->morphTo("Attachment", "attachable");

The Attachment model file is this

class Attachment extends \Eloquent {
     protected $fillable = [

    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


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.