🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Eager Loading

Eager loading loads linked rows together with the main rows. The with method fetches the links up front, instead of one row at a time.

Load tags with tasks

This line loads every task with its tags.

return Task::with('tags')->orderBy('title')->get()
    ->map(function ($task) {
        return $task->title . ': ' . $task->tags
            ->sortBy('name')->pluck('name')->implode(', ');
    })->implode('; ');

Load the project too

This line loads every task with its project. Eager loading loads linked rows together with the main rows.

return Task::with('project')->orderBy('title')->get()
    ->map(function ($task) {
        return $task->title . ': ' . $task->project->name;
    })->implode('; ');

Load two links at once

This line loads tags and projects with the tasks.

return Task::with(['tags', 'project'])->orderBy('title')->get()
    ->map(function ($task) {
        return $task->title . ' (' . $task->project->name . '): '
            . $task->tags->sortBy('name')->pluck('name')->implode(', ');
    })->implode('; ');

Example

Route::get('/tasks/with-tags', function () {
    return Task::with('tags')->orderBy('title')->get()
        ->map(function ($task) {
            return $task->title . ': ' . $task->tags
                ->sortBy('name')->pluck('name')->implode(', ');
        })->implode('; ');
});

Key points

  • Eager loading: loading linked rows together with the main rows.
  • Lazy loading: loading each link only when the code asks for it.
  • Use with('tags') to load tags with the tasks.
  • Use with() with a list to load several links at once.

In this example, the route answers at /tasks/with-tags. The with call loads the tags with the tasks. The query reads every task by title. For each task, the tags are sorted and joined with commas. The joined lines list each task with its tags.

Note

Eager loading stops the same link query from running again and again.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Task::with('tags') do?