PHP
Implement Polymorphic Relationships in Laravel Eloquent
Learn how to create flexible polymorphic relationships in Laravel Eloquent, allowing a model to belong to multiple other models on a single association.
// app/Models/Image.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $fillable = ['url'];
public function imageable()
{
return $this->morphTo();
}
}
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
// app/Models/Video.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
// Usage example
$post = Post::find(1);
foreach ($post->images as $image) {
echo $image->url;
}
$video = Video::find(1);
foreach ($video->images as $image) {
echo $image->url;
}
$image = Image::find(1);
$owner = $image->imageable; // Returns either a Post or Video model
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 either a `Post` model or a `Video` model. The `morphTo()` method on the child model (`Image`) defines the polymorphic relationship, while `morphMany()` or `morphOne()` on the parent models (`Post`, `Video`) define the inverse. Eloquent automatically handles the `imageable_id` and `imageable_type` columns to store the parent's ID and model class name.