PHP

Define Flexible Relationships with Eloquent Polymorphic Relations

Master polymorphic relationships in Laravel Eloquent to enable a model to belong to multiple other models on a single association, providing flexible and scalable database structures.

<?php

// Scenario: Images can belong to either Posts or Users.

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

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

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

// Usage examples:

// Associate an image with a post:
$post = Post::find(1);
$post->images()->create(['url' => 'post-image-1.jpg']);

// Associate an image with a user:
$user = User::find(1);
$user->images()->create(['url' => 'user-avatar-1.jpg']);

// Retrieve the 'imageable' parent of an image:
$image = Image::find(1); // This image belongs to a Post
echo $image->imageable->title; // Accesses the Post's title

$image = Image::find(2); // This image belongs to a User
echo $image->imageable->name; // Accesses the User's name

// Get all images for a post:
$postImages = Post::find(1)->images;

// Get all images for a user:
$userImages = User::find(1)->images;
How it works: Polymorphic relationships in Laravel Eloquent allow a single model to belong to multiple other models on a single association. For example, an `Image` model might belong to either a `Post` or a `User`. This is achieved using `morphTo()` on the child model and `morphMany()` (or `morphOne()`) on the parent models. This pattern creates a flexible and scalable database structure, avoiding the need for separate foreign key columns and relationship methods for each potential parent type, simplifying your database schema and code.

Need help integrating this into your project?

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

Hire DigitalCodeLabs