Skip to content

Instantly share code, notes, and snippets.

@royteusink
Created November 12, 2024 06:59
Show Gist options
  • Save royteusink/c2c3e3d4629ad6e1f95e2d2f04722852 to your computer and use it in GitHub Desktop.
Save royteusink/c2c3e3d4629ad6e1f95e2d2f04722852 to your computer and use it in GitHub Desktop.
Spatie LaravelData nested value cast with dot notation
use Spatie\LaravelData\Casts\Cast;
use Spatie\LaravelData\Casts\IterableItemCast;
use Spatie\LaravelData\Support\Creation\CreationContext;
use Spatie\LaravelData\Support\DataProperty;

class ValueCast implements Cast, IterableItemCast
{
    public function __construct(
        protected ?string $value = null,
    ) {}

    public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): mixed
    {
        return $this->castValue($value);
    }

    public function castIterableItem(DataProperty $property, mixed $value, array $properties, CreationContext $context): mixed {
        return $this->castValue($value);
    }

    protected function castValue(mixed $value): ?string {
        return data_get($value, $this->value);
    }
}
class ProductData extends Data {
  #[WithCast(ValueCast::class, 'value')]
  public ?string $brand_property; // will return 'Nike'
}
  • Product
    • brandProperty: BelongsTo
      • { value: 'Nike', id: 'xxxx-xxxx', ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment