Replace ReactionCounter & ReactionTotal observers with attribute casting #244
-
One of the possible things I want to remove - They were very useful before adding default Right now they are covering only one case - when you are trying to create counter with $total = $reactant->reactionTotal()->create([
'count' => null,
'weight => null,
]);
$counter = $reactant->reactionCounters()->create([
'reaction_type_id' => $reactionType->getId(),
'count' => null,
'weight' => null,
]); While these code will create models with default $total = $reactant->reactionTotal()->create();
$counter = $reactant->reactionCounters()->create([
'reaction_type_id' => $reactionType->getId(),
]); But we have a way to define default values for nulls. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Solution №1Magic Eloquent Model methods. public function setCountAttribute(
int | null $count,
): void {
$this->attributes['count'] = $count ?? self::COUNT_DEFAULT;
}
public function setWeightAttribute(
float | null $weight,
): void {
$this->attributes['weight'] = $weight ?? self::WEIGHT_DEFAULT;
} |
Beta Was this translation helpful? Give feedback.
-
Solution №2Eloquent Model attribute casters. protected $casts = [
'count' => IntegerCast::class,
'weight' => FloatCast::class,
]; final class IntegerCast implements CastsAttributes
{
/**
* Cast the given value.
*
* @param array<string, mixed> $attributes
*/
public function get(
Model $model,
string $key,
mixed $value,
array $attributes,
): int {
return $value;
}
/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(
Model $model,
string $key,
mixed $value,
array $attributes,
): int {
return intval($value);
}
} |
Beta Was this translation helpful? Give feedback.
-
Solution №3public function count(): Attribute
{
return Attribute::make(
set: fn (int | null $value) => $value ?? self::COUNT_DEFAULT,
);
}
public function weight(): Attribute
{
return Attribute::make(
set: fn (float | null $value) => $value ?? self::WEIGHT_DEFAULT,
);
} |
Beta Was this translation helpful? Give feedback.
Solution №3