PHP

Implementing Polymorphic One-to-Many Relationships in Laravel Eloquent

Discover how to use polymorphic relationships to allow a model to belong to multiple other models on a single association, ideal for comments, tags, or images.

use Illuminate\Database\Eloquent\Model;

// In your Image model (e.g., app/Models/Image.php)
class Image extends Model
{
    protected $fillable = ['url'];

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

// In your Post model (e.g., app/Models/Post.php)
class Post extends Model
{
    protected $fillable = ['title'];

    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}

// In your User model (e.g., app/Models/User.php)
class User extends Model
{
    protected $fillable = ['name', 'email'];

    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}

// Usage example:
$post = Post::create(['title' => 'My First Post']);
$post->images()->create(['url' => 'post-image-1.jpg']);

$user = User::create(['name' => 'John Doe', 'email' => '[email protected]']);
$user->images()->create(['url' => 'user-avatar.png']);

$image = Image::find(1);
$owner = $image->imageable; // This will return either a Post or a User model

echo "Image owner type: " . get_class($owner) . "
";

$userImages = $user->images;
foreach($userImages as $img) {
    echo "User image: " . $img->url . "
";
}
How it works: Polymorphic relationships in Eloquent allow a model to belong to more than one other model on a single association. This snippet shows how to define a `morphTo` method on the child model (e.g., `Image`) and a `morphMany` method on the parent models (e.g., `Post` and `User`). This setup is perfect for scenarios where a single type of resource, like an image or comment, can be associated with various different parent models without needing separate relationship columns for each parent.

Need help integrating this into your project?

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

Hire DigitalCodeLabs