0
0
Laravelframework~10 mins

Many-to-many (belongsToMany) 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 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
BbelongsToMany
ChasOne
DbelongsTo
Attempts:
3 left
💡 Hint
Common Mistakes
Using hasMany instead of belongsToMany
Using belongsTo which is for one-to-many or one-to-one
2fill in blank
medium

Complete the code to attach a role to a user using the many-to-many relationship.

Laravel
$user->roles()->[1]($roleId);
Drag options to blanks, or click blank then click option'
Adetach
Bsync
Cattach
Dsave
Attempts:
3 left
💡 Hint
Common Mistakes
Using detach which removes the link
Using save which is for saving models
3fill in blank
hard

Fix the error in the code to retrieve all roles of a user.

Laravel
$roles = $user->[1];
Drag options to blanks, or click blank then click option'
Aroles
Bget_role
Crole
DgetRoles
Attempts:
3 left
💡 Hint
Common Mistakes
Using singular form 'role' instead of 'roles'
Trying to call a method that doesn't exist
4fill in blank
hard

Fill both blanks to define a many-to-many relationship with a custom pivot table and foreign keys.

Laravel
public function permissions() {
    return $this->[1](Permission::class, '[2]', 'user_id', 'permission_id');
}
Drag options to blanks, or click blank then click option'
AbelongsToMany
BhasMany
Crole_user
Dpermission_user
Attempts:
3 left
💡 Hint
Common Mistakes
Using hasMany instead of belongsToMany
Using wrong pivot table name
5fill in blank
hard

Fill all three blanks to sync roles for a user, replacing existing links.

Laravel
$user->[1]()->[2]([[3]]);
Drag options to blanks, or click blank then click option'
Aroles
Bsync
C1, 2, 3
Dattach
Attempts:
3 left
💡 Hint
Common Mistakes
Using attach instead of sync which adds without removing
Passing a string instead of an array for role IDs