Skip to content

Latest commit

 

History

History
89 lines (75 loc) · 1.9 KB

appending-properties.md

File metadata and controls

89 lines (75 loc) · 1.9 KB
title weight
Appending properties
4

It is possible to add some extra properties to your data objects when they are transformed into a resource:

SongData::from(Song::first())->additional([
    'year' => 1987,
]);

This will output the following array:

[
    'name' => 'Never gonna give you up',
    'artist' => 'Rick Astley',
    'year' => 1987,
]

When using a closure, you have access to the underlying data object:

SongData::from(Song::first())->additional([
    'slug' => fn(SongData $songData) => Str::slug($songData->title),
]);

Which produces the following array:

[
    'name' => 'Never gonna give you up',
    'artist' => 'Rick Astley',
    'slug' => 'never-gonna-give-you-up',
]

It is also possible to add extra properties by overwriting the with method within your data object:

class SongData extends Data
{
    public function __construct(
        public int $id,
        public string $title,
        public string $artist
    ) {
    }

    public static function fromModel(Song $song): self
    {
        return new self(
            $song->id,
            $song->title,
            $song->artist
        );
    }
    
    public function with()
    {
        return [
            'endpoints' => [
                'show' => action([SongsController::class, 'show'], $this->id),
                'edit' => action([SongsController::class, 'edit'], $this->id),
                'delete' => action([SongsController::class, 'delete'], $this->id),
            ]
        ];
    }
}

Now each transformed data object contains an endpoints key with all the endpoints for that data object:

[
    'id' => 1,
    'name' => 'Never gonna give you up',
    'artist' => 'Rick Astley',
    'endpoints' => [
        'show' => 'https://spatie.be/songs/1',
        'edit' => 'https://spatie.be/songs/1',
        'delete' => 'https://spatie.be/songs/1',
    ],
]