Bird
Raised Fist0
Laravelframework~20 mins

Many-to-many (belongsToMany) in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Many-to-many Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel Eloquent many-to-many relationship code?
Consider two models, User and Role, connected by a many-to-many relationship using belongsToMany. Given the code below, what will return $user->roles->pluck('name'); output if the user has roles 'Admin' and 'Editor'?
Laravel
<?php
class User extends Model {
    public function roles() {
        return $this->belongsToMany(Role::class);
    }
}

$user = User::find(1);
return $user->roles->pluck('name');
Anull
B["Admin"]
C["Admin", "Editor"]
D[]
Attempts:
2 left
💡 Hint
Remember that belongsToMany returns a collection of related models.
❓ state_output
intermediate
2:00remaining
What is the value of $pivot after accessing a many-to-many relationship?
In Laravel, when accessing a many-to-many relationship, the intermediate table data is available via the pivot property. Given the code below, what will return $user->roles->first()->pivot->created_at; output?
Laravel
<?php
$user = User::find(1);
// Assume roles relationship is defined with timestamps on pivot
return $user->roles->first()->pivot->created_at;
Anull
BAn error because pivot does not exist
CThe user's created_at timestamp
DThe timestamp when the role was attached to the user (e.g., '2024-04-01 12:00:00')
Attempts:
2 left
💡 Hint
Pivot contains data from the intermediate table, including timestamps if enabled.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a many-to-many relationship with a custom pivot table name?
You want to define a many-to-many relationship between Post and Tag models using a pivot table named post_tags. Which code snippet correctly sets this up?
Apublic function tags() { return $this->belongsToMany(Tag::class, 'post_tags'); }
Bpublic function tags() { return $this->belongsToMany(Tag::class)->using('post_tags'); }
Cpublic function tags() { return $this->belongsToMany('post_tags'); }
Dpublic function tags() { return $this->belongsToMany(Tag::class, 'tags_posts'); }
Attempts:
2 left
💡 Hint
The second parameter of belongsToMany is the pivot table name.
🔧 Debug
advanced
2:00remaining
Why does this many-to-many relationship query cause an error?
Given the code below, why does calling $user->roles()->attach(5); cause an error?
Laravel
<?php
class User extends Model {
    public function roles() {
        return $this->belongsToMany(Role::class);
    }
}

$user = User::find(1);
$user->roles()->attach(5);
AThe pivot table does not exist or is misnamed, so attach fails.
BThe <code>roles</code> table does not have a primary key.
CThe <code>roles</code> relationship is missing the <code>withTimestamps()</code> method.
DThe <code>attach</code> method requires an array, not a single ID.
Attempts:
2 left
💡 Hint
Check if the pivot table exists and is named correctly.
🧠 Conceptual
expert
2:00remaining
How does Laravel determine the pivot table name in a many-to-many relationship by default?
When you define a many-to-many relationship using belongsToMany without specifying a pivot table name, how does Laravel decide which table to use?
AIt uses a table named 'pivot' by default.
BIt uses the alphabetical order of the two related model table names joined by an underscore.
CIt uses the name of the first model's table with '_pivot' appended.
DIt requires you to always specify the pivot table name explicitly.
Attempts:
2 left
💡 Hint
Think about how Laravel names pivot tables conventionally.

Practice

(1/5)
1. What does the belongsToMany() method define in a Laravel model?
easy
A. A polymorphic relationship between models
B. A one-to-one relationship between two models
C. A one-to-many relationship from one model to another
D. A many-to-many relationship between two models

Solution

  1. Step 1: Understand relationship types in Laravel

    Laravel provides different methods to define relationships: one-to-one, one-to-many, many-to-many, and polymorphic.
  2. Step 2: Identify the purpose of belongsToMany()

    The belongsToMany() method specifically defines a many-to-many relationship where both models can have multiple related models.
  3. Final Answer:

    A many-to-many relationship between two models -> Option D
  4. Quick Check:

    belongsToMany() = many-to-many [OK]
Hint: belongsToMany means many-to-many link between models [OK]
Common Mistakes:
  • Confusing belongsToMany with hasOne or hasMany
  • Thinking it defines one-to-one relationships
  • Assuming it creates a polymorphic relation
2. Which of the following is the correct syntax to define a many-to-many relationship in a Laravel model named Post related to Tag?
easy
A. public function tags() { return $this->belongsToMany(Tag::class); }
B. public function tags() { return $this->hasMany(Tag::class); }
C. public function tags() { return $this->hasOne(Tag::class); }
D. public function tags() { return $this->morphToMany(Tag::class); }

Solution

  1. Step 1: Recall the method for many-to-many relationships

    In Laravel, many-to-many relationships use the belongsToMany() method inside the model.
  2. Step 2: Match the syntax to the correct method

    The correct syntax is public function tags() { return $this->belongsToMany(Tag::class); } to link Post and Tag models.
  3. Final Answer:

    public function tags() { return $this->belongsToMany(Tag::class); } -> Option A
  4. Quick Check:

    belongsToMany() syntax = public function tags() { return $this->belongsToMany(Tag::class); } [OK]
Hint: Use belongsToMany() for many-to-many syntax [OK]
Common Mistakes:
  • Using hasMany instead of belongsToMany
  • Using hasOne which is one-to-one
  • Confusing morphToMany with belongsToMany
3. Given the following code in a Laravel model User:
public function roles() {
    return $this->belongsToMany(Role::class);
}

$user = User::find(1);
$roles = $user->roles()->pluck('name');
echo $roles->toJson();
What will be the output if user 1 has roles named "admin" and "editor"?
medium
A. Syntax error
B. ["1","2"]
C. ["admin","editor"]
D. null

Solution

  1. Step 1: Understand the belongsToMany relationship usage

    The roles() method returns all roles related to the user via the pivot table.
  2. Step 2: Analyze the pluck and toJson methods

    The pluck('name') extracts the 'name' field from each related role, returning a collection of role names. toJson() converts this collection to a JSON string.
  3. Final Answer:

    ["admin","editor"] -> Option C
  4. Quick Check:

    pluck('name') + toJson() = role names JSON [OK]
Hint: pluck('name') gets names; toJson outputs JSON array [OK]
Common Mistakes:
  • Expecting IDs instead of names
  • Thinking roles() returns null if no roles
  • Confusing pluck with get
4. What is wrong with this Laravel many-to-many relationship definition in the Product model?
public function categories() {
    return $this->hasMany(Category::class);
}
medium
A. The method name should be singular, like category()
B. It should use belongsToMany() instead of hasMany()
C. The related model class name is incorrect
D. No return statement is needed

Solution

  1. Step 1: Identify the relationship type

    Products and categories usually have a many-to-many relationship, so belongsToMany() is the correct method.
  2. Step 2: Check the method used

    The code uses hasMany(), which defines a one-to-many relationship, not many-to-many.
  3. Final Answer:

    It should use belongsToMany() instead of hasMany() -> Option B
  4. Quick Check:

    Many-to-many needs belongsToMany(), not hasMany() [OK]
Hint: Many-to-many always uses belongsToMany() [OK]
Common Mistakes:
  • Using hasMany for many-to-many
  • Naming method singular for plural relation
  • Omitting return statement
5. You have two models, Student and Course, linked by a many-to-many relationship using a pivot table course_student. You want to attach a course with ID 5 to a student with ID 3 and also store the enrollment date in the pivot. Which code snippet correctly does this?
hard
A. $student = Student::find(3); $student->courses()->attach(5, ['enrolled_at' => now()]);
B. $student = Student::find(3); $student->courses()->save(5, ['enrolled_at' => now()]);
C. $student = Student::find(3); $student->courses()->sync(5, ['enrolled_at' => now()]);
D. $student = Student::find(3); $student->courses()->attach([5]);

Solution

  1. Step 1: Understand attaching in many-to-many with pivot data

    The attach() method adds a record to the pivot table and accepts the related model ID plus an array of extra pivot data.
  2. Step 2: Analyze each option

    $student = Student::find(3); $student->courses()->attach(5, ['enrolled_at' => now()]); correctly uses attach(5, ['enrolled_at' => now()]). $student = Student::find(3); $student->courses()->save(5, ['enrolled_at' => now()]); uses save() which expects a model instance, not an ID. $student = Student::find(3); $student->courses()->sync(5, ['enrolled_at' => now()]); uses sync() incorrectly with extra data. $student = Student::find(3); $student->courses()->attach([5]); attaches without pivot data.
  3. Final Answer:

    $student = Student::find(3); $student->courses()->attach(5, ['enrolled_at' => now()]); -> Option A
  4. Quick Check:

    attach(id, pivotData) = $student = Student::find(3); $student->courses()->attach(5, ['enrolled_at' => now()]); [OK]
Hint: Use attach(id, pivotData) to add with extra pivot info [OK]
Common Mistakes:
  • Using save() with ID instead of model instance
  • Using sync() incorrectly with pivot data
  • Forgetting to pass pivot data array
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard