Skip to content

Commit 9ec5d7e

Browse files
DarkGhostHuntershaedrichtaylorotwell
authored
Adds AsColection::map() section (#10327)
* Adds `AsColection::map()` section As part of [#55383](laravel/framework#55383). * Added more clarification * More clarification * Update eloquent-mutators.md Co-authored-by: Sebastian Hädrich <[email protected]> * Adds openinh PHP on full class * Better, almost final, clarification. * Minor change to the Option example so it makes sense * Better clarification about serialization * formatting --------- Co-authored-by: Sebastian Hädrich <[email protected]> Co-authored-by: Taylor Otwell <[email protected]>
1 parent 4d09ace commit 9ec5d7e

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

eloquent-mutators.md

+68
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,74 @@ protected function casts(): array
449449
}
450450
```
451451

452+
The `of` method may be used to indicate collection items should be mapped into a given class via the collection's [`mapInto` method](/docs/{{version}}/collections#method-mapinto):
453+
454+
```php
455+
use App\ValueObjects\Option;
456+
use Illuminate\Database\Eloquent\Casts\AsCollection;
457+
458+
/**
459+
* Get the attributes that should be cast.
460+
*
461+
* @return array<string, string>
462+
*/
463+
protected function casts(): array
464+
{
465+
return [
466+
'options' => AsCollection::of(Option::class)
467+
];
468+
}
469+
```
470+
471+
When mapping collections to objects, the object should implement the `Illuminate\Contracts\Support\Arrayable` and `JsonSerializable` interfaces to define how their instances should be serialized into the database as JSON:
472+
473+
```php
474+
<?php
475+
476+
namespace App\ValueObjects;
477+
478+
use Illuminate\Contracts\Support\Arrayable;
479+
use JsonSerilizable;
480+
481+
class Option implements Arrayable, JsonSerializable
482+
{
483+
/**
484+
* Create a new Option instance.
485+
*/
486+
public function __construct(
487+
public string $name,
488+
public mixed $value,
489+
public bool $isLocked = false
490+
) {
491+
//
492+
}
493+
494+
/**
495+
* Get the instance as an array.
496+
*
497+
* @return array{name: string, data: string, is_locked: bool}
498+
*/
499+
public function toArray(): array
500+
{
501+
return [
502+
'name' => $this->name,
503+
'value' => $this->value,
504+
'is_locked' => $this->isLocked,
505+
];
506+
}
507+
508+
/**
509+
* Specify the data which should be serialized to JSON.
510+
*
511+
* @return array{name: string, data: string, is_locked: bool}
512+
*/
513+
public function jsonSerialize(): array
514+
{
515+
return $this->toArray();
516+
}
517+
}
518+
```
519+
452520
<a name="date-casting"></a>
453521
### Date Casting
454522

0 commit comments

Comments
 (0)