// 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. "; }