0
0
Laravelframework~10 mins

Why relationships model real data in Laravel - Test Your Understanding

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 in a Laravel model.

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

Complete the code to define the inverse of a one-to-many relationship in a Laravel model.

Laravel
public function user() {
    return $this->[1](User::class);
}
Drag options to blanks, or click blank then click option'
AhasMany
BbelongsToMany
ChasOne
DbelongsTo
Attempts:
3 left
💡 Hint
Common Mistakes
Using hasMany instead of belongsTo
Confusing belongsToMany with belongsTo
3fill in blank
hard

Fix the error in the code to correctly define a many-to-many relationship in a Laravel model.

Laravel
public function roles() {
    return $this->[1](Role::class);
}
Drag options to blanks, or click blank then click option'
AhasMany
BbelongsTo
CbelongsToMany
DhasOne
Attempts:
3 left
💡 Hint
Common Mistakes
Using hasMany which is for one-to-many
Using belongsTo which is for inverse one-to-many
4fill in blank
hard

Fill both blanks to define a one-to-one relationship and access the related model's attribute.

Laravel
public function profile() {
    return $this->[1](Profile::class);
}

$name = $user->profile->[2];
Drag options to blanks, or click blank then click option'
AhasOne
BbelongsTo
Cname
Demail
Attempts:
3 left
💡 Hint
Common Mistakes
Using belongsTo instead of hasOne
Accessing an attribute that does not exist
5fill in blank
hard

Fill all three blanks to create a dictionary of post titles and their authors' emails for posts with more than 100 likes.

Laravel
return collect($posts)->filter(fn($post) => $post->likes > [1])
    ->mapWithKeys(fn($post) => [
        $post->[2] => $post->user->[3]
    ]);
Drag options to blanks, or click blank then click option'
A100
Btitle
Cemail
Dlikes
Attempts:
3 left
💡 Hint
Common Mistakes
Using likes as key instead of title
Using user name instead of email