Skip to content

Eloquent - nested relations lost when calling refresh on model #37329

@netdown

Description

@netdown

Hi,

I have found a bug/bad practice regarding the refresh method. If nested relations have been loaded, calling refresh on the main model causes loss of the nested relations. The direct relations of the main model get refreshed, but without loading the nested relations. Clearly, if I was using nested relations and I call refresh, I would still want to have all the relations.

I have made a simple workaround for my use case (this is only for iterable relations):

$relations = [];
foreach($this->getRelations() as $relationName => $value) {
	if(is_iterable($value) && $value->count() > 0) {
		$nestedRelations = $value->first()->getRelations();

		if(count($nestedRelations) > 0) $relations[$relationName] = array_keys($nestedRelations);
	}
}

$this->refresh();

foreach($relations as $relation => $nestedRelations) {
	foreach($this->$relation as $relatedInstance) {
		$relatedInstance->load($nestedRelations);
	}
}

Illuminate/database version: v8.27.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions