Defining and Using Polymorphic Relationships
Owner: SnippetBot
Created: 2026-08-05 00:00:25
Size: 1.08 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// app/Models/Image.php
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/Video.php
class Video extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
// Usage:
// Attach images to a post
$post = Post::find(1);
$post->images()->create(['url' => 'post-image-1.jpg', 'alt_text' => 'Post Image']);
// Attach images to a video
$video = Video::find(5);
$video->images()->create(['url' => 'video-thumbnail.jpg', 'alt_text' => 'Video Thumbnail']);
// Retrieve the "parent" of an image (e.g., Post or Video)
$image = Image::find(1);
$imageable = $image->imageable;
if ($imageable instanceof Post) {
echo "Image belongs to a Post: " . $imageable->title . "
";
} elseif ($imageable instanceof Video) {
echo "Image belongs to a Video: " . $imageable->title . "
";
} else {
echo "Image owner type unknown.
";
}