Eloquent Polymorphic Relation

Polymorphic relations allow a model to belong to more than one other model in a single association. A really simple example is a users table and a posts table and they both could be related to one other table called photos. So in the photos table we’ll have some columns that would specify the model in which they belong to and the ID of that record. For example, we have one photo record that belongs to the post model with an ID of 1, and this belongs to the user model with an ID of 2.

We are going to have a photos table which will need a new Photo role which we’ll build a migration at the same time:

php artisan make:model Photo -m

Open up the migration and add these to the up function:

            $table->string('path');
            $table->integer('imageable_id');
            $table->string('imageable_type');

Now migrate this

php artisan migrate

Create a few photos in your database. This one is a little more complicated than usual. imageable_id is the ID of the post OR user. imageable_type lets us know which model to reference in this format (App\Models\User).

Now we need to set the relationship starting in the Photo model. Write this:

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

Now we need to set the other tables. Let’s set Post model to pull photos:

    public function photos() {
        return $this->morphMany('App\Models\Photo','imageable');
    }

Add this exact piece of code to the User model as well.

Let’s pull out a user’s photo:

Route::get('/user/photos', function(){
    $user = User::find(1);
    foreach($user->photos as $photo){
        echo $photo;
    }
});

Let’s pull out a post’s photo:

Route::get('/post/photos', function(){
    $post = Post::find(1);
    foreach($post->photos as $photo){
        echo $photo;
    }
});

Leave a Reply

Your email address will not be published. Required fields are marked *