Open utterances-bot opened 2 years ago
Assuming you have a collection of 1000 $model
instances and each $model
has one ->relation
, you'll cause 1000 additional queries triggered from the view because $model->relation
is lazy-loaded whenever the view is rendered.
@foreach($models as $model)
{{ $model->relation->property }}
@endforeach
Eager-load your relationships with the built-in Model::with()
method before (!!!) you display them. This will only cause:
1 query to load all the models
1 additional query with a well formed WHERE id IN(...)
condition
$models = Model::with('relation')->get()
@foreach($models as $model)
{{ $model->relation->property }}
@endforeach
Laravel eloquent relationships explained
Eloquent ORM is one of the most exciting and powerful built-in features in Laravel. Before we start we’ve to understand, what ORM means. ORM means object relational mapper. It handles database operations by representing data as objects.
https://codesource.io/laravel-eloquent-relationships-explained/