Last active
July 8, 2021 16:07
-
-
Save owenconti/2c3ef7bbf827117630cd44ef76dd8d37 to your computer and use it in GitHub Desktop.
Temporary relationship trait for Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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