Laravel - Relationships - Eager Loading

When accessing Eloquent relationships as properties, the related models are "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the "N + 1" query problem. To illustrate the N + 1 query problem, consider a Book model that "belongs to" to an Author model:

    
    belongsTo(Author::class);
        }
    }
	

Now, let's retrieve all books and their authors:

    
    use App\Models\Book;
    
    $books = Book::all();
    
    foreach ($books as $book) {
        echo $book->author->name;
    }
	

This loop will execute one query to retrieve all of the books within the database table, then another query for each book in order to retrieve the book's author. So, if we have 25 books, the code above would run 26 queries: one for the original book, and 25 additional queries to retrieve the author of each book.

Thankfully, we can use eager loading to reduce this operation to just two queries. When building a query, you may specify which relationships should be eager loaded using the with method:

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

For this operation, only two queries will be executed - one query to retrieve all of the books and one query to retrieve all of the authors for all of the books:

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