🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel One to Many

A one-to-many link joins one parent row to many child rows. One project holds many tasks, and each task belongs to one project.

Read the children

This line reads the tasks of the Home project.

return Project::where('name', 'Home')->first()
    ->tasks()->orderBy('title')->pluck('title')->implode(', ');

Read the parent

This line reads the project of one task. A one-to-many link joins one parent row to many child rows.

return Task::where('title', 'Write report')->first()->project->name;

Define the parent side

The Project model names its many tasks.

public function tasks(): HasMany
{
    return $this->hasMany(Task::class);
}

Define the child side

The Task model names its one project.

public function project(): BelongsTo
{
    return $this->belongsTo(Project::class);
}

Example

Route::get('/projects', function () {
    return Project::orderBy('name')->get()->map(function ($project) {
        return $project->name . ': ' . $project->tasks()
            ->orderBy('title')->pluck('title')->implode(', ');
    })->implode('; ');
});

Key points

  • Relationship: a link between rows in two tables.
  • One-to-many: one parent row joined to many child rows.
  • Use hasMany() in the parent model for its children.
  • Use belongsTo() in the child model for its parent.
  • Use $project->tasks to read the children of a project.

In this example, the route answers at /projects. The query reads every project by name. For each project, the tasks call reads its tasks. The task titles are sorted and joined with commas. The joined lines list each project with its tasks.

Note

The child table holds the parent id in a project_id column.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which method links a parent to its many children?