0

I'm using ValueObject casting as an ID of my model. Everything works fine when I get a record from database, however when it coming to saving, the ID is null. If I comment "casts" out, ID is correct.

Example:

$game = new Game($data);
$game->created_by = $userId; // Id ValueObject
$game->save();
dd($game);
// attributes:
// "id" => null,
// "created_by" => Id{#value: 10},

Id ValueObject:

class Id
{
 public function get($model, $key, $value, $attributes)
 {
    $this->value = $value;

    return $this;
 }

 public function set($model, $key, $value, $attributes)
 {
    $this->value = $value;
 }

 public function value(): int
 {
    return $this->value;
 }

 public function __toString()
 {
    return (string) $this->value;
 }
}

Model:

class Game extends Model
{
  protected $casts = [
    'id' => Id::class
  ];
}

What can I do with it?
Thanks in advance

VG-Electronics
  • 230
  • 2
  • 16
  • You're attempting to cast the `id` attribute, not the `created_by` attribute in your `$casts` array. That's why the id is returning null. – IGP May 15 '21 at 19:33
  • My question is about ID field, "created_by" was just an example of ValueObject usage. – VG-Electronics May 15 '21 at 22:01
  • And how is the id field kept in the database? What is its type? – IGP May 15 '21 at 22:29
  • 1
    Following the example in the laravel documentation, your Id class seems to be missing something. It should implement the `\Illuminate\Contracts\Database\Eloquent\CastsAttributes` interface. That might be the source of your problems. – IGP May 15 '21 at 22:31

1 Answers1

0

Okey, I think that there should be a ValueObject and a CastingObject, I ended up with something similar to this:

class Game extends Model
{
  protected $casts = [
    'id' => IdCast::class
  ];
}

class IdCast implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return new Id(
            $attributes['id']
        );
    }

    public function set($model, $key, $value, $attributes)
    {
        return [
            'id' => $value
        ];
    }
}

class Id
{
    private $value;

    public function __construct($id)
    {
        $this->value = $id;
    }

    public function value(): int
    {
        return $this->value;
    }

    public function __toString()
    {
        return (string) $this->value;
    }
}
VG-Electronics
  • 230
  • 2
  • 16