PHP
Implementing Polymorphic Relationships in Laravel Eloquent
Master polymorphic relationships in Laravel Eloquent, allowing a single model to belong to multiple different models on a single association, promoting flexibility.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
// The 'polymorphic' model (e.g., Image, Comment, Tag)
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
// Models that can 'own' an Image
class Post extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
class User extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
// Example Database Migration for 'images' table:
// Schema::create('images', function (Blueprint $table) {
// $table->id();
// $table->string('url');
// $table->morphs('imageable'); // Adds imageable_id (INT) and imageable_type (VARCHAR)
// $table->timestamps();
// });
// Usage examples:
$post = Post::find(1);
$post->images()->create(['url' => 'post-image-1.jpg']);
$user = User::find(1);
$user->images()->create(['url' => 'user-profile-pic.png']);
$image = Image::find(1);
// Access the parent model, whether it's a Post or a User
$owner = $image->imageable; // Returns either a Post or User model instance
echo "Image URL: {$image->url}, Owned by: " . get_class($owner);
How it works: Polymorphic relationships in Laravel Eloquent allow a model to belong to more than one other model on a single association. For example, an `Image` model might belong to either a `Post` or a `User`. This is achieved by storing two columns on the polymorphic model's table: `_id` (the ID of the owning model) and `_type` (the class name of the owning model). The `morphTo()` method is used on the polymorphic model, and `morphMany()` (or `morphOne()`) is used on the owning models, simplifying your database schema and model interactions for flexible associations.