Performance: Many-to-many (belongsToMany)
This affects database query performance and page load speed by controlling how many queries and joins are executed to fetch related data.
$users = User::with('roles')->get(); // eager loads roles in one query foreach ($users as $user) { $roles = $user->roles; // no extra queries }
foreach ($users as $user) { $roles = $user->roles; // triggers a query per user (N+1 problem) }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Lazy loading many-to-many relations | Minimal DOM nodes | 1 reflow after data arrives | Paint delayed by slow data fetch | [X] Bad |
| Eager loading many-to-many relations | Minimal DOM nodes | 1 reflow after data arrives | Paint happens sooner with data ready | [OK] Good |
belongsToMany() method define in a Laravel model?belongsToMany()belongsToMany() method specifically defines a many-to-many relationship where both models can have multiple related models.Post related to Tag?belongsToMany() method inside the model.public function tags() { return $this->belongsToMany(Tag::class); } to link Post and Tag models.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"?roles() method returns all roles related to the user via the pivot table.pluck('name') extracts the 'name' field from each related role, returning a collection of role names. toJson() converts this collection to a JSON string.Product model?
public function categories() {
return $this->hasMany(Category::class);
}belongsToMany() is the correct method.hasMany(), which defines a one-to-many relationship, not many-to-many.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?attach() method adds a record to the pivot table and accepts the related model ID plus an array of extra pivot data.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.Pass the test and this pattern moves unknown