Control which properties are included in your API resources using lazy evaluation
Sometimes you don’t want all properties included when transforming a data object. With lazy properties, you can include properties only when needed:
class AlbumData extends Data{ /** * @param Lazy|Collection<int, SongData> $songs */ public function __construct( public string $title, public Lazy|Collection $songs, ) { } public static function fromModel(Album $album): self { return new self( $album->title, Lazy::create(fn() => SongData::collect($album->songs)) ); }}
The songs key won’t be included when transforming:
class UserData extends Data{ public function __construct( public string $title, public Lazy|SongData $favorite_song, ) { } public static function fromModel(User $user): self { return new self( $user->title, Lazy::create(fn() => SongData::from($user->favorite_song)) ); }}
#[AutoLazy]class UserData extends Data{ public function __construct( public string $title, public Lazy|SongData $favorite_song, ) { }}
Automatically create lazy properties for model relations:
class UserData extends Data{ public function __construct( public string $title, #[AutoWhenLoadedLazy] public Lazy|SongData $favoriteSong, ) { }}
Specify the relation name if it differs:
class UserData extends Data{ public function __construct( public string $title, #[AutoWhenLoadedLazy('favoriteSong')] public Lazy|SongData $favorite_song, ) { }}
AlbumData::from(Album::first())->only('songs'); // only show `songs`AlbumData::from(Album::first())->except('songs'); // show everything except `songs`