php
38 lines · 5 steps
Polymorphic comments in Laravel with morphTo
One Comment model attaches to both Posts and Videos through Eloquent's polymorphic morphTo relationship.
Explained by
highlit
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6use Illuminate\Database\Eloquent\Relations\BelongsTo;
7use Illuminate\Database\Eloquent\Relations\MorphTo;
8
9class Comment extends Model
10{
11 protected $fillable = ['body', 'user_id'];
12
13 public function commentable(): MorphTo
14 {
15 return $this->morphTo();
16 }
17
18 public function author(): BelongsTo
19 {
20 return $this->belongsTo(User::class, 'user_id');
21 }
22}
23
24class Post extends Model
25{
26 public function comments(): MorphMany
27 {
28 return $this->morphMany(Comment::class, 'commentable')->latest();
29 }
30}
31
32class Video extends Model
33{
34 public function comments(): MorphMany
35 {
36 return $this->morphMany(Comment::class, 'commentable')->latest();
37 }
38}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Polymorphic relations let one table serve many parent types without a foreign key per type.
- 2morphTo on the child pairs with morphMany on each parent to complete the two-way link.
- 3A relationship method can return a chained query so every access carries default constraints like ordering.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/polymorphic-comments-in-laravel-with-morphto-explained-php-91ac/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.