0
0
Laravelframework~10 mins

One-to-many (hasMany) 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 one-to-many relationship method in a Laravel model.

Laravel
public function posts() {
    return $this->[1](Post::class);
}
Drag options to blanks, or click blank then click option'
AhasOne
BbelongsTo
ChasMany
DbelongsToMany
Attempts:
3 left
💡 Hint
Common Mistakes
Using belongsTo instead of hasMany
Using hasOne which is for one-to-one relationships
2fill in blank
medium

Complete the code to retrieve all posts for a user using the relationship.

Laravel
$user = User::find(1);
$posts = $user->[1];
Drag options to blanks, or click blank then click option'
Aposts
Bcomments
Cpost
Dprofile
Attempts:
3 left
💡 Hint
Common Mistakes
Using singular 'post' which does not exist
Using unrelated properties like 'comments' or 'profile'
3fill in blank
hard

Fix the error in the relationship method by completing the code correctly.

Laravel
public function comments() {
    return $this->[1](Comment::class);
}
Drag options to blanks, or click blank then click option'
AhasMany
BhasOne
CbelongsTo
DbelongsToMany
Attempts:
3 left
💡 Hint
Common Mistakes
Using belongsTo which is for inverse relationships
Using hasOne which is for one-to-one relationships
4fill in blank
hard

Fill both blanks to define a one-to-many relationship with a custom foreign key.

Laravel
public function orders() {
    return $this->[1](Order::class, '[2]');
}
Drag options to blanks, or click blank then click option'
AhasMany
BbelongsTo
Cuser_id
Dorder_id
Attempts:
3 left
💡 Hint
Common Mistakes
Using belongsTo instead of hasMany
Using wrong foreign key like order_id
5fill in blank
hard

Fill all three blanks to create a one-to-many relationship with a custom foreign key and local key.

Laravel
public function reviews() {
    return $this->[1](Review::class, '[2]', '[3]');
}
Drag options to blanks, or click blank then click option'
AhasMany
Buser_id
Cid
DbelongsTo
Attempts:
3 left
💡 Hint
Common Mistakes
Using belongsTo instead of hasMany
Mixing up foreign key and local key names