> For the complete documentation index, see [llms.txt](https://idt-nida.gitbook.io/developer-guideline/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://idt-nida.gitbook.io/developer-guideline/must-you-know/comparison/lazy-loading-vs-eager-loading.md).

# Lazy Loading vs Eager Loading

## 🆚 Comparison

| Feature        | Lazy Loading                                      | Eager Loading                                                           |
| -------------- | ------------------------------------------------- | ----------------------------------------------------------------------- |
| Definition     | Loads related objects only when accessed          | Loads related objects immediately                                       |
| Performance    | Can reduce initial load time                      | May increase initial load time                                          |
| Query Control  | More granular control over fetched data           | Less control over fetched data                                          |
| Complexity     | Simpler to implement initially                    | More complex to implement correctly                                     |
| Network Calls  | May require multiple queries                      | Usually requires fewer queries                                          |
| Usage Scenario | Suitable for large datasets with selective access | Suitable for small datasets or when all related data is needed together |

## 🅰️ Lazy Loading

{% hint style="success" %}
**การใช้งาน** : ใช้เมื่อต้องการประหยัดทรัพยากรและเพิ่มประสิทธิภาพในการโหลดข้อมูล เนื่องจากข้อมูลจะถูกโหลดเฉพาะเมื่อมีความจำเป็นจริง ๆ

**ข้อดี** : ช่วยลดการใช้ทรัพยากรในขณะที่ไม่จำเป็น และ ช่วยเพิ่มประสิทธิภาพของแอปพลิเคชันโดยลดเวลาการโหลดข้อมูลที่ไม่ได้ใช้

**ข้อเสีย** : อาจทำให้เกิดปัญหาการเรียกข้อมูลซ้ำซ้อนได้ หรือ อาจทำให้เกิดปัญหาการแก้ไขข้อมูลที่มีการอ้างอิงระหว่างข้อมูล
{% endhint %}

```php
$project = Project::find(1);
$user = $project->user;
```

## 🅱️ Eager Loading

{% hint style="success" %}
**การใช้งาน** : ใช้เมื่อต้องการความแม่นยำในการดึงข้อมูลแบบเต็มรูปแบบตั้งแต่ต้น ซึ่งอาจช่วยลดเวลาในการเข้าถึงข้อมูลที่ซับซ้อน

**ข้อดี** : ช่วยให้การเข้าถึงข้อมูลที่ซับซ้อนเร็วขึ้น และ ลดความซับซ้อนในการจัดการข้อมูลที่มีความสัมพันธ์มาก

**ข้อเสีย** : ใช้ทรัพยากรมากขึ้นในการโหลดข้อมูลเป็นจำนวนมาก หรือ อาจทำให้ล่าช้าในการโหลดหน้าเว็บหรือการทำงานที่ต้องการข้อมูลบางส่วนเท่านั้น
{% endhint %}

```php
$projects = Project::with('user')->get();

foreach ($projects as $project) {
    $user = $project->user;
}
```
