Bad Practice Example
class Book extends Model
{
public function author()
{
return $this->belongsTo(Author::class);
}
}
$books = Book::all();
foreach ($books as $book) {
echo $book->author->name;
}What To Do Instead
class Book extends Model
{
/**
* Get the author that wrote the book.
*/
public function author()
{
return $this->belongsTo(Author::class);
}
}
$books = Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}إستخدام lazy loading لجلب البيانات كما في المثال الأول يؤدي لبطئ في الموقع، وكذلك إستهلاك أعلى للذاكرة، لذلك من المفضل إستخدام eager loading.