PHP
Implementing Flexible Polymorphic Relationships in Laravel Eloquent
Discover how to build dynamic and flexible 'one-to-many' or 'one-to-one' relationships where a model can belong to multiple other models on a single association using Eloquent polymorphic relations.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
/**
* Get the parent imageable model (post or user).
*/
public function imageable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get all of the post's images.
*/
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
class User extends Model
{
/**
* Get all of the user's images.
*/
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
// Usage example:
// $post = Post::find(1);
// foreach ($post->images as $image) {
// echo $image->url;
// }
// $user = User::find(1);
// foreach ($user->images as $image) {
// echo $image->url;
// }
How it works: Polymorphic relationships allow a single model (e.g., `Image`) to belong to multiple other models (e.g., `Post` or `User`) using a single association. The `morphTo()` method on the `Image` model defines the dynamic relationship, while `morphMany()` on `Post` and `User` models indicates they can have many images. This approach reduces database table count and simplifies relationship management for shared resources across different entities, making your application more flexible and scalable.