PHP

Define and Query Polymorphic Relations in Laravel Eloquent

Understand how to set up and query polymorphic one-to-many relationships in Laravel Eloquent, allowing a single model to belong to multiple different types of models on a single association.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class Image extends Model
{
    /**
     * Get the parent imageable model (post or user).
     */
    public function imageable(): MorphTo
    {
        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->path . "
";
}

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

$image = Image::find(1);
echo $image->imageable->title; // Access parent (Post or User) attributes dynamically
How it works: Polymorphic relations allow a model to belong to more than one other model on a single association. In this example, an `Image` can belong to either a `Post` or a `User`. The `Image` model defines a `morphTo` relationship, while `Post` and `User` models define `morphMany` relationships. Laravel handles the necessary `_id` and `_type` columns on the `images` table to store the ID of the parent model and its class name, respectively. This enables flexible and efficient data structures where related models share a common trait or asset.

Need help integrating this into your project?

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

Hire DigitalCodeLabs