laravel: using eager loading with models

We use models a lot when developing projects with Laravel. By defining the relationships between the tables within the models, we ensure that the relevant data is brought over the database in a practical way. We can take advantage of the Eager Loading feature to increase performance and get faster results when performing operations with related models. For this, we can use the with() method when creating a query from the related models:

// Load book's author
Book::with('author')->get();

// Load book's author and publisher
Book::with('author', 'publisher')->get();

// Load book's author and author's contact details
Book::with('author.contacts')->get();

// Load book's author with id, name and book_id columns
Book::with('author:id,name,book_id')->get();

// Load book's author with id, name and book_id columns
Book::with(['posts' => function ($query) {
 $query->where('title', 'like', '%php%');
}])->get();

// Always load author relationship
class Book extends Model
{
 protected $with = ['author'];
}