Skip to content

Adds AsColection::map() section #10327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: 12.x
Choose a base branch
from
97 changes: 97 additions & 0 deletions eloquent-mutators.md
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,103 @@ protected function casts(): array
}
```

Collection items can be mapped into an specific class instance by using a second parameter. or the `map()` method if you want to use the base Collection class.

```php
use App\ValueObjects\Option;
use Illuminate\Database\Eloquent\Casts\AsCollection;

/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'options' => AsCollection::map(Option::class)
];
}
```

For better control on how the items should be constructed once inside the Collection, you may set a callable that receives each item as an array.

```php
use App\ValueObjects\Option;
use Illuminate\Database\Eloquent\Casts\AsCollection;

/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'options' => AsCollection::map([Option::class, 'fromArray']),
];
}
```

When handling a collection of objects, you should implement both `Illuminate\Contracts\Support\Arrayable` and `JsonSerializable` interfaces in the object class to control how these should be serialized into the database as JSON.

```php
<?php

namespace App\ValueObjects;

use Illuminate\Contracts\Support\Arrayable;
use JsonSerilizable;

class Option implements Arrayable, JsonSerializable
{
/**
* Create a new Option instance.
*/
public function __construct(
public string $name,
public mixed $value,
public bool $isLocked = false
) {
//
}

/**
* Get the instance as an array.
*
* @return array{name: string, data: string, is_locked: bool}
*/
public function toArray(): array
{
return [
'name' => $this->name,
'value' => $this->value,
'is_locked' => $this->isLocked,
];
}

/**
* Specify data which should be serialized to JSON.
*
* @return array{name: string, data: string, is_locked: bool}
*/
public function jsonSerialize(): array
{
return $this->toArray();
}

/**
* Create a new instance from an array.
*
* @param array{name: string, data: string, is_locked: bool} $data
*/
public function fromArray(array $data): static
{
return new static($data['name'], $data['value'], $data['is_locked']);
}
}
```

<a name="date-casting"></a>
### Date Casting

Expand Down