This trait provides a temporary($relationship) method on your model for you to access relationships without adding them to the list of loaded relationships.
If the relationship is already loaded, it is returned directly. If the relationship is not loaded, it will be loaded, removed from the list of loaded relationships, and then returned.
The function is wrapped in Spatie’s once package to add memoization. This allows the same temporary relationship to be called multiple times without multiple DB queries.
<?php namespaceApp\Models\Traits; traitTemporaryRelationships { /** * Returns the value of the given relationship from the current model. * * If the relation is already loaded, it is returned directly. * * If the relation is not loaded, it is loaded, then removed * from the list of loaded relations, and then returned. * * The function is memoized so accessing the same temporary * relation within a request will only make one query. */ publicfunctiontemporary(string$relation) { return once(function () use ($relation) { if ($this->relationLoaded($relation)) { return$this->{$relation}; } $relationValue = $this->getRelationValue($relation); $this->unsetRelation($relation); return$relationValue; }); } }