Laravel Many to Many
A many-to-many link joins rows on both sides to many rows. One task can hold many tags, and one tag can mark many tasks.
Read a task's tags
This line reads the tags of the Buy milk task.
return Task::where('title', 'Buy milk')->first()
->tags()->orderBy('name')->pluck('name')->implode(', ');Read a tag's tasks
This line reads the tasks marked urgent. A many-to-many link joins rows on both sides to many rows.
return Tag::where('name', 'urgent')->first()
->tasks()->orderBy('title')->pluck('title')->implode(', ');Add a link
These lines link a new task to the home tag.
$task = Task::create(['title' => 'Read book', 'done' => false]);
$task->tags()->attach(Tag::where('name', 'home')->first());
return $task->tags()->orderBy('name')->pluck('name')->implode(', ');Define the link
Both models name the link with belongsToMany.
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}Example
Route::get('/tasks/tags', function () {
return Task::orderBy('title')->get()->map(function ($task) {
return $task->title . ': ' . $task->tags()
->orderBy('name')->pluck('name')->implode(', ');
})->implode('; ');
});Key points
- Many-to-many: rows on both sides joined to many rows.
- Pivot table: a small table that stores the links between two tables.
- Use belongsToMany() in both models for the link.
- Use attach() to add a link between two rows.
- Use sync() to set the exact links for a row.
In this example, the route answers at /tasks/tags. The query reads every task by title. For each task, the tags call reads its tags. The tag names are sorted and joined with commas. The joined lines list each task with its tags.
Note
The pivot table holds one task id and one tag id per link.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does attach() do?