Laravel eager load cheat sheet

Categorized as Laravel Tagged

What is eager loading? This is an excellent concept for eloquent model in Laravel, when you retrieve the items, you are provided with all the related items at the same query. This eliminates the famous N+1 query problem.

// Eager loads the 'author' relationship in
// the Book model
$books = Book::with('author')->get();

// Eager loads the 'author' and 'publisher' relationships in
// the Book model
$books = Book::with(['author', 'publisher'])->get();

// Eager loads the 'author' relationship in
// the Book model and the 'contacts' relationship
// in the Author model
$books = Book::with('author.contacts')->get();

// Eager loads the 'author' relationship in
// the Book model with only the columns "id",
// "name" and "book_id"
$books = Book::with('author:id, name, book_id')->get();

// Eager loads by default the "author" relationship
class Book extends Model 
{
  protected $with = ['author'];
}

// You can disable default relationships with "without"
$books = Book::without('author')->get();

// Overwrite the $with property for a single query
$books = Book::withOnly('genre')->get();

// Eager loads with constraints.
// Only eager loads the posts that have the word "code"
// in the title
$users = User::with(['posts' => function($query) {
  $query->where('title', 'like', '%code%');
}])->get();

Leave a reply

Your email address will not be published.