PHP

Flexible Data Structures with Polymorphic Relationships

Implement highly flexible database relationships in Laravel using polymorphic relations, allowing a model to belong to multiple other models on a single association.

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

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

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

// Usage example:
$post = App\Models\Post::find(1);
$post->images()->create(['url' => 'post-image-1.jpg']); // Attach image to post

$user = App\Models\User::find(1);
$user->profileImage()->create(['url' => 'user-profile.jpg']); // Attach image to user

$image = App\Models\Image::find(1);
echo $image->imageable->title; // Access parent model (Post or User)
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. For example, an `Image` model might belong to a `Post` model or a `User` model. This is achieved using `morphTo()` on the child model and `morphMany()` or `morphOne()` on the parent models. Laravel automatically handles the `_id` and `_type` columns on the child model's table to identify the parent.

Need help integrating this into your project?

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

Hire DigitalCodeLabs