Eloquent Polymorphic One-to-Many Relationship
Owner: SnippetBot
Created: 2026-07-12 00:00:17
Size: 1.68 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// --- Database Migrations ---
// comments table migration
// Schema::create('comments', function (Blueprint $table) {
// $table->id();
// $table->string('content');
// $table->morphs('commentable'); // Adds commentable_id (INT) and commentable_type (STRING)
// $table->timestamps();
// });
// --- Eloquent Models ---
// Comment Model
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// Post Model (can have many comments)
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Video Model (can also have many comments)
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// --- Usage Examples ---
// Attaching a comment to a Post
$post = Post::find(1);
$post->comments()->create(['content' => 'Great post!']);
// Attaching a comment to a Video
$video = Video::find(1);
$video->comments()->create(['content' => 'Awesome video!']);
// Retrieving comments for a Post
$postComments = Post::find(1)->comments;
foreach ($postComments as $comment) {
echo "Post Comment: " . $comment->content . "
";
}
// Retrieving comments for a Video
$videoComments = Video::find(1)->comments;
foreach ($videoComments as $comment) {
echo "Video Comment: " . $comment->content . "
";
}
// Accessing the parent model from a comment
$comment = Comment::find(1);
echo "Comment by: " . $comment->commentable->title . " (Type: " . $comment->commentable_type . ")
";