Handling Dynamic Relationships with Eloquent Polymorphic Relations
Owner: SnippetBot
Created: 2026-09-21 00:00:23
Size: 1.39 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
// 1. Define models (e.g., Post, Video, Comment)
// app/Models/Comment.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Comment extends Model
{
protected $fillable = ['body', 'commentable_id', 'commentable_type'];
// Define the polymorphic relationship
public function commentable(): MorphTo
{
return $this->morphTo();
}
}
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Post extends Model
{
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// app/Models/Video.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Video extends Model
{
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// 2. Usage examples:
$post = App\Models\Post::find(1);
$post->comments()->create(['body' => 'Great post!']);
$video = App\Models\Video::find(5);
$video->comments()->create(['body' => 'Awesome video!']);
// Access the commentable parent from a comment
$comment = App\Models\Comment::find(1);
$parent = $comment->commentable; // Can be a Post or a Video instance
echo get_class($parent); // e.g., "App\\Models\\Post"