You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class NameCast implements CastsAttributes
{
public function get($model, string $key, $value, $attributes)
{
return Name::create($value);
}
public function set($model, string $key, $setName, $attributes)
{
if (!$setName instanceof Name) {
throw new \InvalidArgumentException('Parameter $setName must be instance of ' . Name::class);
}
return [
$key => $setName->value()
];
}
}
Name Value Object:
class Name
{
public const MIN_LENGTH = 2;
protected $name;
private function __construct(string $name)
{
if (mb_strlen($name) < self::MIN_LENGTH) {
throw new \InvalidArgumentException('Name must has at least ' . self::MIN_LENGTH . ' characters');
}
$this->name = $name;
}
public static function create(string $name): Name
{
return new static($name);
}
public function value()
{
return $this->name;
}
}
The text was updated successfully, but these errors were encountered:
I get the same result and was also a bit surprised at this. I'm suspecting that this is the expected behavior and that you should implement Illuminate\Contracts\Support\Arrayable on your value object. But it would be good to clarify this in the docs.
Gonna wait to see what @taylorotwell says about this.
Objects are expected to implement Arrayable / JsonSerializable to solve this. I thought I documented that but maybe not. If not we can update the documentation.
Description:
The problem is that value objects are not casted back when call
Client::toJson()
.So, for example we have next model:
Accessing
name
property gives usName
value object:When we call
$client->toJson()
, we get empty object instead of primitive value:{"id":7,"name":{},"email_verified_at":null}
Steps To Reproduce:
Client Eloquent Model:
Name Cast:
Name Value Object:
The text was updated successfully, but these errors were encountered: