Eager load hasMany & belongsTo (circular reference/infinite loop)
There is a without()
method: https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Builder.html#method_without
Placing without()
on both sides of a relationship worked.
class Property extends EloquentModel {
protected $with = ['images'];
public function images()
{
return $this->hasMany(Image::class)->without('property');
}
}
class Image extends EloquentModel {
protected $with = ['property'];
public function property()
{
return $this->belongsTo(Property::class)->without('images');
}
public function getAlt()
{
return $this->property->title;
}
}
UPDATE:
Even though using without()
easily avoid the infinite loop issue, through years of experience with Laravel I realize it is bad practice to set $with
in the model as it causes relationships to always load. Hence leading to circular reference/infinite loop
Rather, always use with()
to explicitly specify necessary relationships to be eager loaded, however deep necessary (relationship of relationship)
For example:
$user = User::with('images' => function ($query) {
$query->with('property' => function ($query) {
$query->with('deeperifneeded' => function ($query) {
//...
});
});
]);
Note: May need to remove without()