The way you are trying to access related records in loop could create N + 1 problem
As per official docs When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem
You could eager load your related data as
$results = ParentModel::with('records')
->where(...) /* If there are any filters for ParentModel */
->get();
For eager loading only 2 queries will be executed to get your data for main model and related model. Each row in $results
will a collection of related records which you can iterate to list details of each related object.
To get filtered rows of related model you could modify with()
method as
$results = ParentModel::with(['records' => function ($query) {
$query->where('status','=','success');
}])
->where(...) /* If there are any filters for ParentModel */
->get();
To get filtered rows of ParentModel on basis of related records you could use whereHas
$results = ParentModel::with('records')
->where(...) /* If there are any filters for ParentModel */
->whereHas('records', function ($query) {
$query->where('status','=','success');
})->get();