Laravel 8 morph relationship

By Ved Prakash N | Apr 06, 2023 | Laravel
Share :

https://www.fundaofwebit.com/post/laravel-8-morph-relationship

Explain laravel 8 morph relationship


In Laravel 8, Morph relationships allow you to associate a single model with multiple other models on different tables without having to specify a different relationship method for each model. This can be useful when you have entities that can be related to multiple types of other entities.

For example, let's say you have a 'comments' table that can be associated with multiple other tables such as 'posts', 'videos', and 'articles'. Rather than creating separate relationships for each, you can use a Morph relationship.

To use a Morph relationship, you'll need to add two columns to your 'comments' table:

1. 'commentable_id': The ID of the related model
2. 'commentable_type': The type of the related model (e.g., "App\Models\Post", "App\Models\Video", etc.)

To define a Morph relationship in your model, you'll use the 'morphTo' method. Here's an example:

class Comment extends Model
{
    /**
     * Get the owning commentable model.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}
This method returns an instance of the related model, based on the commentable_type and commentable_id values in the comments table.

To define the inverse of the relationship on the related model (e.g., 'Post', 'Video', etc.), you'll use the 'morphMany' or 'morphOne' method. Here's an example for a 'Post' model:

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

This method defines a one-to-many relationship between the Post model and the Comment model, using the commentable method on the Comment model.

You can also use a 'morphToMany' method to define a many-to-many relationship using a polymorphic pivot table.

Overall, Morph relationships in Laravel 8 provide a flexible and efficient way to associate a model with multiple other models on different tables.

https://www.fundaofwebit.com/post/laravel-8-morph-relationship

Share this blog on social platforms