Laravel Relationships: Eager Loading

Alleviates the N + 1 query problem.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}
$books = App\Book::all();

foreach ($books as $book) {
    echo $book->author->name;
}
$books = App\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}
Select * from books

select * from authors where id in (1, 2, 3, 4, 5, ...)

Eager Loading Multiple Relationships

$books = App\Book::with(['author', 'publisher'])->get();

Nested Eager Loading

$books = App\Book::with('author.contacts')->get();

Eager Loading Specific Columns

$users = App\Book::with('author:id,name')->get();

Constraining Eager Loads

$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');
}])->get();
$users = App\User::with(['posts' => function ($query) {
    $query->orderBy('created_at', 'desc');
}])->get();

Lazy Eager Loading

$books = App\Book::all();

if ($someCondition) {
    $books->load('author', 'publisher');
}
$books->load(['author' => function ($query) {
    $query->orderBy('published_date', 'asc');
}]);
Public function format(Book $book)
{
    $book->loadMissing('author');

    return [
        'name' => $book->name,
        'author' => $book->author->name
    ];
}

Laravel Relationships: Eager Loading — Structure map

Clickable & Draggable!

Laravel Relationships: Eager Loading — Related pages: