0
0
Laravelframework~10 mins

Polymorphic relationships in Laravel - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a polymorphic relation method in a Laravel model.

Laravel
public function image() {
    return $this->[1]('imageable');
}
Drag options to blanks, or click blank then click option'
AbelongsTo
BhasMany
CmorphTo
DhasOne
Attempts:
3 left
💡 Hint
Common Mistakes
Using hasMany or belongsTo instead of morphTo causes errors.
Forgetting to pass the relation name 'imageable' to the method.
2fill in blank
medium

Complete the code to define a polymorphic relation in the Image model.

Laravel
public function imageable() {
    return $this->[1]();
}
Drag options to blanks, or click blank then click option'
AhasOne
BbelongsTo
ChasMany
DmorphTo
Attempts:
3 left
💡 Hint
Common Mistakes
Using belongsTo instead of morphTo breaks the polymorphic relation.
Adding parameters to morphTo in the child model is unnecessary.
3fill in blank
hard

Fix the error in the polymorphic relation definition in the Post model.

Laravel
public function comments() {
    return $this->[1]('commentable');
}
Drag options to blanks, or click blank then click option'
AmorphMany
BhasMany
CbelongsToMany
DmorphTo
Attempts:
3 left
💡 Hint
Common Mistakes
Using hasMany instead of morphMany breaks polymorphic behavior.
Using morphTo is incorrect in the parent model for one-to-many.
4fill in blank
hard

Fill both blanks to complete the polymorphic relation in the Video model.

Laravel
public function tags() {
    return $this->[1]('taggable');
}

public function taggable() {
    return $this->[2]();
}
Drag options to blanks, or click blank then click option'
AmorphToMany
BbelongsToMany
CmorphTo
DhasMany
Attempts:
3 left
💡 Hint
Common Mistakes
Using belongsToMany instead of morphToMany breaks polymorphic many-to-many.
Using hasMany instead of morphToMany is incorrect for many-to-many polymorphic.
5fill in blank
hard

Fill all three blanks to complete the polymorphic relation and query in Laravel.

Laravel
$comments = Comment::where('[1]_id', $post->id)
    ->where('[2]_type', get_class($post))
    ->get();

$post->[3]()->save(new Comment(['body' => 'Nice post!']));
Drag options to blanks, or click blank then click option'
Acommentable
Ccomments
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong column names breaks the query.
Using singular relation method name instead of plural causes errors.