When fetching any models from the database and then doing any type of processing on the model’s relations, it’s important that we use https://laravel.com/docs/8.x/eloquent-relationships#eager-loading. Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.

Without eager loading, your code might look like this: $comments = Comment::all(); foreach ($comments as $comment ) { print_r($comment->author->name); } The code above would result in 101 database queries because it the results are “lazy loaded”!
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners