PHP

Manage Multiple Relationship Types with Eloquent Polymorphic Relationships

Learn to define and use polymorphic relationships in Laravel Eloquent, allowing a single model to belong to multiple other models on a single association.

// In App/Models/Image.php
class Image extends Model
{
    public function imageable()
    {
        return $this->morphTo();
    }
}

// In App/Models/Post.php
class Post extends Model
{
    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}

// In App/Models/User.php
class User extends Model
{
    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}

// Usage
$post = App\Models\Post::find(1);
foreach ($post->images as $image) {
    echo $image->url . "
";
}

$user = App\Models\User::find(1);
foreach ($user->images as $image) {
    echo $image->url . "
";
}

$image = App\Models\Image::find(1);
echo $image->imageable->name; // Access parent model dynamically
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. For instance, an `Image` model might belong to either a `Post` or a `User`. This snippet illustrates how to define these relationships using `morphTo()` on the child model (`Image`) and `morphMany()` (or `morphOne()`) on the parent models (`Post`, `User`), providing a flexible and efficient way to manage diverse relationships without adding redundant columns.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs