[Eloquent Model] initialize traits after filling model to dynamically add attributes #36141
Replies: 3 comments 8 replies
-
This seems like it could be handled using the 'retrieved' Model event, but I could be wrong. I'm looking into using it for a similar use case. |
Beta Was this translation helpful? Give feedback.
-
Because |
Beta Was this translation helpful? Give feedback.
-
Hi, To give you a little more context:
Right now you can't, as attributes are filled after trait(s) initialization. This is very likely a corner case, but having the data available, would allow a more granular use of Traits. Edit - a solution to this problem
trait XYZTrait
{
public bool $hasXYZTrait = true; // will use this later to easily check if model uses the trait
// ... trait content
public function isExcludedType(): bool
{
if ($this instanceof YourModelToCheck) {
return $this->propertyToCheck === 'valueThatExcludesTrait';
}
return $false;
}
}
$modelHasXYZTrait = property_exists($model, 'hasXYZTrait');
$modelHasActiveTrait = $modelHasXYZTrait && $visitModel->isExcludedType() === false; The |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a way to where we could initialize traits for a model after filling its attributes?
framework/src/Illuminate/Database/Eloquent/Model.php
Lines 166 to 175 in 7395583
The reasoning for this is I want my trait to initialize an attribute that depends on another column.
During
initializeFooTrait()
, the model's attributes isn't filled yet, thus throwing errors.Maybe add something like
finalizeTraits()
where you definefinilizeFooTrait()
in your trait.I'd be very happy to make a PR for this <3
Beta Was this translation helpful? Give feedback.
All reactions