Skip to content

Instantly share code, notes, and snippets.

@owenconti
Last active July 8, 2021 16:07
Show Gist options
  • Save owenconti/2c3ef7bbf827117630cd44ef76dd8d37 to your computer and use it in GitHub Desktop.
Save owenconti/2c3ef7bbf827117630cd44ef76dd8d37 to your computer and use it in GitHub Desktop.
Temporary relationship trait for Laravel
<?php
namespace App\Models\Traits;
trait TemporaryRelationships
{
/**
* 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.
*/
public function temporary(string $relation)
{
return once(function () use ($relation) {
if ($this->relationLoaded($relation)) {
return $this->{$relation};
}
$relationValue = $this->getRelationValue($relation);
$this->unsetRelation($relation);
return $relationValue;
});
}
}
<?php
namespace App\Models;
use App\Models\Traits\TemporaryRelations;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use TemporaryRelations;
public function someMethod()
{
return $this->temporary('author');
}
public function author()
{
return $this->belongsTo(User::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment