TITLE: Create Data Object from Array - PHP DESCRIPTION: This snippet illustrates creating a `SongData` object from an associative array using the static `from` method. The array keys correspond to the data object's properties. This method provides a convenient way to populate data objects from external data sources. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/creating-a-data-object.md#_snippet_2 LANGUAGE: php CODE: ``` SongData::from(['title' => 'Never gonna give you up', 'artist' => 'Rick Astley']); ``` ---------------------------------------- TITLE: Manually Validating Data with Laravel Data DESCRIPTION: This snippet demonstrates how to manually validate an array of data against a Laravel Data object's inferred or defined rules. If validation fails, a `ValidationException` is thrown. This is useful when validation doesn't happen automatically, such as validating data from a source other than a request. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_0 LANGUAGE: php CODE: ``` SongData::validate( ['title' => 'Never gonna give you up'] ); // ValidationException will be thrown because 'artist' is missing ``` ---------------------------------------- TITLE: Define Data Object Extending Dto - PHP DESCRIPTION: Defines a simple data object `SongData` that extends the `Dto` class instead of the `Data` class. The `Dto` class represents a simpler DTO with less built-in functionality. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/creating-a-data-object.md#_snippet_14 LANGUAGE: php CODE: ``` class SongData extends Dto { public function __construct( public string $title, public string $artist, ) { } } ``` ---------------------------------------- TITLE: Manually Validating and Creating Data Object in Laravel Data DESCRIPTION: This snippet shows how to validate data and, if successful, automatically create an instance of the Laravel Data object. It's a convenient way to combine validation and object creation in one step when validation isn't handled automatically. If validation passes, an instance of the data object is returned; otherwise, a `ValidationException` is thrown. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_1 LANGUAGE: php CODE: ``` SongData::validateAndCreate( ['title' => 'Never gonna give you up', 'artist' => 'Rick Astley'] ); // returns a SongData object ``` ---------------------------------------- TITLE: Defining Authorization Logic in Laravel Data Class DESCRIPTION: Similar to Laravel form requests, this snippet shows how to define authorization logic for a Laravel Data object by implementing a static `authorize()` method. This method should return `true` if the current user is authorized to perform the action related to this data object, or `false` otherwise. If it returns `false`, an `AuthorizationException` is thrown. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_9 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, ) { } public static function authorize(): bool { return Auth::user()->name === 'Ruben'; } } ``` ---------------------------------------- TITLE: Create Data Object from Eloquent Model - PHP DESCRIPTION: This snippet demonstrates how to create a `SongData` object from an Eloquent model instance using the `from` method. The package automatically extracts the relevant properties from the model. Assumes a `Song` model with accessible properties that match the `SongData` object properties. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/creating-a-data-object.md#_snippet_3 LANGUAGE: php CODE: ``` SongData::from(Song::firstOrFail($id)); ``` ---------------------------------------- TITLE: Creating a Basic Data Object with `laravel-data` in PHP DESCRIPTION: This snippet demonstrates how to create a simple data object class (`SongData`) by extending the `Spatie\LaravelData\Data` base class. It utilizes PHP 8's constructor property promotion to define public properties (`title` and `artist`) directly in the constructor signature. Extending `Data` unlocks features like automatic transformations, validation, and TypeScript generation for this object. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/introduction.md#_snippet_0 LANGUAGE: php CODE: ``` use Spatie\LaravelData\Data; class SongData extends Data { public function __construct( public string $title, public string $artist, ) { } } ``` ---------------------------------------- TITLE: Converting a Single Data Object to Array in PHP DESCRIPTION: Demonstrates how to transform a single Laravel Data object into an array using the toArray() method. This converts a Song model instance to a SongData object and then to an array representation. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/from-data-to-array.md#_snippet_0 LANGUAGE: php CODE: ``` SongData::from(Song::first())->toArray(); ``` ---------------------------------------- TITLE: Defining Data Class with Nested Data Objects in Laravel Data DESCRIPTION: This snippet defines a Laravel Data class (`SingleData`) that contains properties which are themselves other Laravel Data objects (`ArtistData`, `SongData`). The package automatically handles the validation of these nested data objects when validating the parent object, applying their respective rules. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_10 LANGUAGE: php CODE: ``` class SingleData{ public function __construct( public ArtistData $artist, public SongData $song, ) { } } ``` ---------------------------------------- TITLE: Defining Data Class for Auto Rule Inferring in Laravel Data DESCRIPTION: This code snippet defines a simple Laravel Data class (`ArtistData`) with public properties. The package automatically infers validation rules based on the PHP type hints (`string`, `int`, `?string`). Non-nullable primitive types default to `required`, while nullable types default to `nullable` plus the type. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_4 LANGUAGE: php CODE: ``` class ArtistData extends Data{ public function __construct( public string $name, public int $age, public ?string $genre, ) { } } ``` ---------------------------------------- TITLE: Creating a Data Object from a Form Request in a Laravel Controller (PHP) DESCRIPTION: Shows how to create a `SongData` object manually within a controller method using the static `SongData::from($request)` method, passing in a validated `SongRequest` instance. This approach allows leveraging Laravel's Form Requests for authorization and initial validation before creating the data object. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/request-to-data-object.md#_snippet_3 LANGUAGE: php CODE: ``` class UpdateSongController { public function __invoke( Song $model, SongRequest $request ){ $model->update(SongData::from($request)->all()); return redirect()->back(); } } ``` ---------------------------------------- TITLE: Defining Manual Validation Rules in Laravel Data (PHP) DESCRIPTION: This snippet illustrates how to manually define property validation rules in a Laravel Data object by implementing a static rules method. It replaces automatic rule inference, requiring explicit rule arrays for each property. Properties like title and artist are made required strings, and developers must ensure proper array syntax for rule definitions. No external dependencies are required, and the method returns the expected rule arrays for integration with Laravel's validation system. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/manual-rules.md#_snippet_0 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, ) { } public static function rules(): array { return [ 'title' => ['required', 'string'], 'artist' => ['required', 'string'], ]; } } ``` ---------------------------------------- TITLE: Injecting and Using a Data Object in a Laravel Controller (PHP) DESCRIPTION: Demonstrates injecting the `SongData` object directly into a controller method (`__invoke`) signature. The `laravel-data` package automatically resolves, populates, and validates the `$data` object from the current HTTP request before the method body executes. The example then uses `$data->all()` to update an Eloquent model. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/request-to-data-object.md#_snippet_2 LANGUAGE: php CODE: ``` class UpdateSongController { public function __invoke( Song $model, SongData $data ){ $model->update($data->all()); return redirect()->back(); } } ``` ---------------------------------------- TITLE: Instantiating Nested Spatie Data From Array (PHP) DESCRIPTION: Using the magic 'from' method, you can create an instance of AlbumData directly from a nested array structure. The Data package automatically handles hydrating the nested ArtistData object from its corresponding array representation. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/nesting.md#_snippet_2 LANGUAGE: php CODE: ``` AlbumData::from([ 'title' => 'Never gonna give you up', 'artist' => [ 'name' => 'Rick Astley', 'age' => 22 ] ]); ``` ---------------------------------------- TITLE: Instantiating Nested Spatie Data Objects (PHP) DESCRIPTION: This snippet shows how to create an instance of the nested AlbumData object by passing scalar values for the title and an instance of the nested ArtistData object for the artist property. This is the standard object-oriented approach to creating data objects. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/nesting.md#_snippet_1 LANGUAGE: php CODE: ``` new AlbumData( 'Never gonna give you up', new ArtistData('Rick Astley', 22) ); ``` ---------------------------------------- TITLE: Creating a DataCollection with Data Objects - Laravel Data - PHP DESCRIPTION: Shows how to collect Eloquent model results and convert them into a DataCollection pre-defined by the package. This enables additional methods like include and extra collection features. Requires Spatie\LaravelData\DataCollection and SongData. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/collections.md#_snippet_9 LANGUAGE: php CODE: ``` use Spatie\LaravelData\DataCollection; SongData::collect(Song::all(), DataCollection::class); ``` ---------------------------------------- TITLE: Resolving Data Object from Laravel Container with Validation DESCRIPTION: This snippet demonstrates resolving a Laravel Data object from the application container. When a data object is resolved this way, the package automatically attempts to fill its properties from the current request's data. If the request data does not pass the data object's validation rules (inferred, manual, or attribute-based), a `ValidationException` is thrown. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_8 LANGUAGE: php CODE: ``` app(SongData::class); ``` ---------------------------------------- TITLE: Using Optional Creation - PHP DESCRIPTION: Demonstrates the use of the `optional` method to handle null values. Returns `null` if the input is null. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/creating-a-data-object.md#_snippet_12 LANGUAGE: php CODE: ``` SongData::optional(null); // returns null ``` ---------------------------------------- TITLE: Returning a Data Object in Controller (PHP) DESCRIPTION: Demonstrates how a Laravel Data object is returned from a controller method, which automatically converts it to a JSON response. It uses the `SongData::from()` method to create the data object from a Song model instance. No specific dependencies are needed beyond Laravel Data and a Song model. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/from-data-to-resource.md#_snippet_0 LANGUAGE: php CODE: ``` class SongController { public function show(Song $model) { return SongData::from($model); } } ``` ---------------------------------------- TITLE: Validating Data When Default Values Are Present in Laravel Data DESCRIPTION: This snippet shows calling the `validate` method on a `SongData` class which has default values defined for its properties. When validating an array that is missing a property with a default value (like 'artist' in this case), the 'required' rule is not applied to that missing property, as it would be automatically filled by the default. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_15 LANGUAGE: php CODE: ``` SongData::validate( ['title' => 'Giving Up On Love'] ); ``` ---------------------------------------- TITLE: Resolving a Data Object from the Laravel Container (PHP) DESCRIPTION: Illustrates resolving a `SongData` object directly from the Laravel service container using the `app()` helper function. When resolved this way, the package automatically attempts to populate the object's properties from the current request data and performs validation. A validation exception is thrown if incompatible data is found. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/request-to-data-object.md#_snippet_4 LANGUAGE: php CODE: ``` app(SongData::class); ``` ---------------------------------------- TITLE: Generated Validation Rules for Nested Data Objects in Laravel Data DESCRIPTION: This snippet shows the validation rules generated by Laravel Data for a class (`SingleData`) containing nested data objects (`ArtistData`, `SongData`). Rules for nested objects are prefixed with the property name (e.g., 'artist.name'), and the nested property itself gets an 'array' rule. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_11 LANGUAGE: php CODE: ``` [ 'artist' => ['array'], 'artist.name' => ['required', 'string'], 'artist.age' => ['required', 'integer'], 'artist.genre' => ['nullable', 'string'], 'song' => ['array'], 'song.title' => ['required', 'string'], 'song.artist' => ['required', 'string'], ] ``` ---------------------------------------- TITLE: Conditional Property Methods with Boolean Conditions in PHP DESCRIPTION: Shows how to conditionally include, exclude, only include, or except properties from a Laravel Data object using a boolean condition as the second parameter. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/lazy-properties.md#_snippet_26 LANGUAGE: php CODE: ``` AlbumData::from(Album::first())->includeWhen('songs', auth()->user()->isAdmin); AlbumData::from(Album::first())->excludeWhen('songs', auth()->user()->isAdmin); AlbumData::from(Album::first())->onlyWhen('songs', auth()->user()->isAdmin); AlbumData::from(Album::first())->except('songs', auth()->user()->isAdmin); ``` ---------------------------------------- TITLE: Creating Data Objects with Default Values DESCRIPTION: Examples of instantiating Data objects using default values or overriding them with custom values through the from() method. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/defaults.md#_snippet_2 LANGUAGE: php CODE: ``` SongData::from(); SongData::from(['title' => 'Giving Up On Love', 'date' => CarbonImmutable::create(1988, 4, 15)]); ``` ---------------------------------------- TITLE: Defining a Data Object with Optional Properties in PHP DESCRIPTION: Shows how to define a SongData class with a required title property and an optional artist property using the Optional type from Spatie's Laravel Data package. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/optional-properties.md#_snippet_0 LANGUAGE: php CODE: ``` use Spatie\LaravelData\Optional; class SongData extends Data { public function __construct( public string $title, public string|Optional $artist, ) { } } ``` ---------------------------------------- TITLE: Generated Validation Rules for Nested Data Collection in Laravel Data DESCRIPTION: This snippet shows the validation rules generated by Laravel Data for a class (`AlbumData`) containing a collection of nested data objects (`SongData`). Rules for items within the collection are prefixed with the property name followed by `.*.` (e.g., 'songs.*.title'), and the collection property itself gets 'required' and 'array' rules. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_13 LANGUAGE: php CODE: ``` [ 'title' => ['required', 'string'], 'songs' => ['required', 'array'], 'songs.*.title' => ['required', 'string'], 'songs.*.artist' => ['required', 'string'], ] ``` ---------------------------------------- TITLE: Merging Manual and Automatic Validation Rules with Attribute in Laravel Data (PHP) DESCRIPTION: This code utilizes the MergeValidationRules attribute to combine manually defined rules with those automatically inferred by Laravel Data. The rules method returns custom constraints, such as max:20, while the attribute ensures required and string rules are also merged in. The resulting output rule set includes both automatic and manual components. Dependencies include the MergeValidationRules attribute applied as a PHP 8+ attribute on the data class. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/manual-rules.md#_snippet_2 LANGUAGE: php CODE: ``` #[MergeValidationRules] class SongData extends Data { public function __construct( public string $title, public string $artist, ) { } public static function rules(): array { return [ 'title' => ['max:20'], 'artist' => ['max:20'], ]; } } // The generated rules will look like this [ 'title' => [required, 'string', 'max:20'], 'artist' => [required, 'string', 'max:20'], ] ``` ---------------------------------------- TITLE: Referencing Peer Field for Conditional Rule PHP DESCRIPTION: Illustrates how to reference another property within the same data object using its name string. The `RequiredIf('title', 'Never Gonna Give You Up')` attribute makes the 'artist' field required only if the 'title' field has the specified value. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/using-validation-attributes.md#_snippet_3 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, #[RequiredIf('title', 'Never Gonna Give You Up')] public string $artist, ) { } } ``` ---------------------------------------- TITLE: Collecting Arrays into Data Objects - Laravel Data - PHP DESCRIPTION: Demonstrates collecting an array of associative arrays into an array of SongData objects using the collect method. The collect method internally uses the from method of the data class. Expects an array as input and returns an array of corresponding data objects. Requires the Spatie Laravel Data package and a SongData data object class. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/collections.md#_snippet_0 LANGUAGE: php CODE: ``` SongData::collect([ ['title' => 'Never Gonna Give You Up', 'artist' => 'Rick Astley'], ['title' => 'Giving Up on Love', 'artist' => 'Rick Astley'], ]); // returns an array of SongData objects ``` ---------------------------------------- TITLE: Generating TypeScript Definitions via Artisan Command DESCRIPTION: Describes executing the Laravel artisan command 'typescript:transform' to generate the TypeScript files containing the type definitions from annotated PHP data classes. This command consolidates all marked classes into usable TypeScript types for frontend or API schema purposes. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/typescript.md#_snippet_5 LANGUAGE: PHP CODE: ``` php artisan typescript:transform ``` ---------------------------------------- TITLE: Define Data Object with Properties - PHP DESCRIPTION: This code defines a `SongData` object with public properties instead of using a constructor. This alternative approach is perfectly valid. The properties are `title` and `artist`, both declared as strings. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/creating-a-data-object.md#_snippet_5 LANGUAGE: php CODE: ``` class SongData extends Data { public string $title; public string $artist; } ``` ---------------------------------------- TITLE: Generated Validation Rules for Nested Data Structures in Laravel Data (PHP) DESCRIPTION: This snippet illustrates the structure of validation rules produced for a nested data object setup. It demonstrates generated rule arrays for both top-level and nested SongData instances within AlbumData. Rules cover string, required, nullable constraints, array presence, and contain NestedRules for handling child data objects. This aids in understanding output rule formats for complex validated structures. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/manual-rules.md#_snippet_8 LANGUAGE: php CODE: ``` [ 'title' => ['string', 'required'], 'songs' => ['present', 'array'], 'songs.*.title' => ['string', 'required'], 'songs.*.artist' => ['string', 'nullable'], 'songs.*' => [NestedRules(...)], ] ``` ---------------------------------------- TITLE: Overriding the with() Method to Add Custom Endpoints in Laravel Data Resource (PHP) DESCRIPTION: This code defines a SongData class that extends Data and overrides the with() method to append a structured endpoints property to each transformed array. The with() method returns an array of URLs for various routes (show, edit, delete), resolved by the action() helper, parameterized by the object's id. Requires the SongsController class and Laravel's action() function. Inputs include a Song model instance; output is an augmented array representation of the data object with nested endpoints. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/appending-properties.md#_snippet_2 LANGUAGE: php CODE: ``` 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), ] ]; } } ``` ---------------------------------------- TITLE: Appending Additional Static Properties with spatie/laravel-data in PHP DESCRIPTION: This snippet demonstrates how to append extra static properties to a data object after transformation using the additional method provided by the spatie/laravel-data package. Dependencies include the SongData data class, and it expects a Song model instance. The additional method takes an associative array of key-value pairs and returns a data object with those keys included in the output array. Suitable for adding fixed properties at runtime; outputs an array including the supplemental fields. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/appending-properties.md#_snippet_0 LANGUAGE: php CODE: ``` SongData::from(Song::first())->additional([ 'year' => 1987, ]); ``` ---------------------------------------- TITLE: Defining a Data Object with a Nested Collection (AlbumData) in PHP DESCRIPTION: Defines the `AlbumData` class containing a basic `title` property and a `songs` property typed as `DataCollection`. The `#[DataCollectionOf(SongData::class)]` attribute informs the package that the `songs` collection should contain instances of `SongData`, enabling automatic mapping and validation of nested structures. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/request-to-data-object.md#_snippet_5 LANGUAGE: php CODE: ``` class AlbumData extends Data { public function __construct( public string $title, #[DataCollectionOf(SongData::class)] public DataCollection $songs, ) { } } ``` ---------------------------------------- TITLE: Nested Data Object Validation with Relative Context in Laravel Data (PHP) DESCRIPTION: This example shows how to apply validation rules to a nested data structure, such as an AlbumData object containing multiple SongData objects. AlbumData holds a title and an array of songs; SongData validates its own properties using the payload from ValidationContext. This pattern enables precise validation at each level of nesting, handling both array typing and property rules. Expected input is a nested array payload reflecting the album and its songs, and outputs corresponding rule arrays for each nested path. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/manual-rules.md#_snippet_6 LANGUAGE: php CODE: ``` class AlbumData extends Data { /** * @param array $songs */ public function __construct( public string $title, public array $songs, ) { } } class SongData extends Data { public function __construct( public string $title, public ?string $artist, ) { } public static function rules(ValidationContext $context): array { return [ 'title' => ['required'], 'artist' => Rule::requiredIf($context->payload['title'] !== 'Never Gonna Give You Up'), ]; } } ``` ---------------------------------------- TITLE: Validation Rules for Nested Data Collection DESCRIPTION: This demonstrates the validation rules for the `AlbumData` object when it contains a collection of `SongData` objects. The 'songs' property is validated as an array, with each item validated using the `NestedRules` class, which ensures individual validation of the data class for that collection. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/nesting-data.md#_snippet_3 LANGUAGE: php CODE: ``` [ 'title' => ['required', 'string'], 'songs' => ['present', 'array', new NestedRules()], ] ``` ---------------------------------------- TITLE: Applying Local Casts Using Attributes in PHP Data Classes DESCRIPTION: Shows how to declare local casts using attributes inside the constructor of a data class for properties requiring special transformation, such as DateTime and Enum. This allows the automatic creation of complex types from strings. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/casts.md#_snippet_3 LANGUAGE: PHP CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, #[WithCast(DateTimeInterfaceCast::class)] public DateTime $date, #[WithCast(EnumCast::class)] public Format $format, ) { } } ``` ---------------------------------------- TITLE: Validation Rules for Optional Nested Data (Value Provided) DESCRIPTION: The validation rules when a value (even an empty array or null) is provided for the optional nested object key. The 'artist' key is expected to be an array, and its nested properties ('name' and 'age') are validated. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/nesting-data.md#_snippet_9 LANGUAGE: php CODE: ``` [ 'title' => ['required', 'string'], 'artist' => ['array'], 'artist.name' => ['required', 'string'], 'artist.age' => ['required', 'integer'], ] ``` ---------------------------------------- TITLE: Mapping Property Names with MapInputName in Laravel DESCRIPTION: This snippet demonstrates how to map an input property name to a different property name within a Laravel Data object using the `MapInputName` attribute. It maps 'record_company' from an array to the property `$recordCompany`. Requires the Spatie Laravel Data package to be installed. Input is an array, and the output is a data object with mapped property names. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/mapping-property-names.md#_snippet_0 LANGUAGE: php CODE: ``` class ContractData extends Data { public function __construct( public string $name, #[MapInputName('record_company')] public string $recordCompany, ) { } } ``` ---------------------------------------- TITLE: Including Nested Lazy Properties - PHP DESCRIPTION: This snippet shows how to include nested lazy properties using the `include()` method with dot notation. It includes the `name` and `artist` properties of the `songs` collection within the `AlbumData` object. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/lazy-properties.md#_snippet_6 LANGUAGE: php CODE: ``` AlbumData::from(Album::first())->include('songs.name', 'songs.artist'); ``` ---------------------------------------- TITLE: Generating Data Object using make:data command - Shell DESCRIPTION: This shell command generates a new data object named `PostData` using the Laravel Artisan command `make:data`. This command is provided by the Spatie Laravel Data package. The generated object is placed in the default namespace `App\Data`. No specific dependencies are required beyond having Laravel and the Spatie package installed. The output is a newly created data object file within the project's directory structure. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/commands.md#_snippet_0 LANGUAGE: shell CODE: ``` php artisan make:data PostData ``` ---------------------------------------- TITLE: Disable Optional Values in Factory - Laravel Data DESCRIPTION: Demonstrates how to handle optional values within the factory. `withoutOptionalValues()` ensures that missing optional properties are initialized to null rather than as an `Optional` object. The code snippets also highlight the importance of nullable types or default values to prevent "typed property must not be accessed before initialization" errors. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/factories.md#_snippet_5 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, public Optional|null|string $album, ) { } } SongData::factory() ->withoutOptionalValues() ->from(['title' => 'Never gonna give you up', 'artist' => 'Rick Astley']); // album will `null` instead of `Optional` ``` LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, public Optional|string $album, // careful here! public Optional|string $publisher = 'unknown', public Optional|string|null $label, ) { } } $data = SongData::factory() ->withoutOptionalValues() ->from(['title' => 'Never gonna give you up', 'artist' => 'Rick Astley']); $data->toArray(); // ['title' => 'Never gonna give you up', 'artist' => 'Rick Astley', 'publisher' => 'unknown', 'label' => null] $data->album; // accessing the album will throw an error, unless the property is set before accessing it ``` ---------------------------------------- TITLE: Defining Data Class with Mapped Property Name in Laravel Data DESCRIPTION: This snippet demonstrates using the `#[MapInputName]` attribute to map an incoming request/input key ('song_title') to a different internal property name ('title') within a Laravel Data class. Validation rules are generated based on the *mapped* input name. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_17 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( #[MapInputName('song_title')] public string $title, ) { } } ``` ---------------------------------------- TITLE: Defining Eloquent Cast with Laravel Data Object in PHP DESCRIPTION: Shows how to define a custom Eloquent cast on a model attribute using a Laravel Data object class. The 'artist' attribute is cast to an ArtistData object, enabling automatic transformation between arrays and data objects when creating or retrieving model instances. No external dependencies beyond the Spatie Laravel Data package and Laravel Eloquent are required. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/eloquent-casting.md#_snippet_0 LANGUAGE: php CODE: ``` class Song extends Model { protected $casts = [ 'artist' => ArtistData::class, ]; } ``` LANGUAGE: php CODE: ``` Song::create([ 'artist' => new ArtistData(name: 'Rick Astley', age: 22), ]); ``` LANGUAGE: php CODE: ``` Song::create([ 'artist' => [ 'name' => 'Rick Astley', 'age' => 22 ] ]); ``` LANGUAGE: php CODE: ``` Song::findOrFail($id)->artist; // ArtistData object ``` ---------------------------------------- TITLE: Overwriting Automatic Inference with Custom Rules in Laravel Data (PHP) DESCRIPTION: This example demonstrates how specifying rules explicitly in the rules method disables any automatic rule inference for the corresponding properties. Only the listed rules, such as max:20 for the title and artist, are applied. The generated output will contain only these rules and omit default ones like required or string. Use this pattern when precise control over validation rules is necessary. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/manual-rules.md#_snippet_1 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, ) { } public static function rules(): array { return [ 'title' => ['max:20'], 'artist' => ['max:20'], ]; } } // The generated rules will look like this [ 'title' => ['max:20'], 'artist' => ['max:20'], ] ``` ---------------------------------------- TITLE: Applying Basic Validation Attributes PHP DESCRIPTION: Demonstrates how to apply common Laravel validation rules directly as attributes on data object properties (e.g., Uuid, Max, IP, StartsWith). These attributes are automatically merged with the rules inferred from the property type (like 'required', 'string'). The resulting rules for this example would be equivalent to `['uuid' => ['required', 'string', 'uuid'], 'ip' => ['required', 'string', 'max:15', 'ip', 'starts_with:192.']]`. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/using-validation-attributes.md#_snippet_0 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( #[Uuid()] public string $uuid, #[Max(15), IP, StartsWith('192.')] public string $ip, ) { } } ``` ---------------------------------------- TITLE: Defining Nested Laravel Data Objects PHP DESCRIPTION: Provides the structure for a nested data object scenario. The `AlbumData` object contains a `SongData` object, which is used as context to demonstrate how validation rules and field references work with nested data. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/using-validation-attributes.md#_snippet_4 LANGUAGE: php CODE: ``` class AlbumData extends Data { public function __construct( public string $album_name, public SongData $song, ) { } } ``` ---------------------------------------- TITLE: Retrieving Validation Rules Manually for Laravel Data Object DESCRIPTION: This snippet shows how to explicitly retrieve the generated validation rules for a Laravel Data object by calling the static `getValidationRules()` method. It's recommended to pass the payload data being validated to this method, as the payload influences which rules (especially 'required') are included based on default values. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_19 LANGUAGE: php CODE: ``` AlbumData::getValidationRules($payload); ``` ---------------------------------------- TITLE: Defining a Computed Property in a Data Class (PHP) DESCRIPTION: Demonstrates defining a computed property `full_name` in a `SongData` class extending `Spatie\LaravelData\Data`. The `#[Computed]` attribute marks the property, and its value is calculated and assigned within the class constructor based on `first_name` and `last_name` properties. This approach allows deriving values dynamically upon object creation. Note the conditions: the property must be declared solely (not in constructor promotion) and cannot be set directly from input payloads. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/computed.md#_snippet_0 LANGUAGE: php CODE: ``` use Spatie\LaravelData\Attributes\Computed; class SongData extends Data { #[Computed] public string $full_name; public function __construct( public string $first_name, public string $last_name, ) { $this->full_name = "{$this->first_name} {$this->last_name}"; } } ``` ---------------------------------------- TITLE: Create Data Object using `fromMultiple` - PHP DESCRIPTION: Showcases creating a data object using the `fromMultiple` static method. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/creating-a-data-object.md#_snippet_11 LANGUAGE: php CODE: ``` SongData::from('Never gonna give you up', 'Rick Astley'); ``` ---------------------------------------- TITLE: Specifying a Custom Format for a Local Transformer in PHP DESCRIPTION: Demonstrates passing a custom date format ('m-Y') as an argument to the `DateTimeInterfaceTransformer` when applying it locally using the `#[WithTransformer]` attribute. This overrides the default format specified in the configuration. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/transformers.md#_snippet_1 LANGUAGE: php CODE: ``` class ArtistData extends Data{ public function __construct( public string $name, #[WithTransformer(DateTimeInterfaceTransformer::class, format: 'm-Y')] public Carbon $birth_date ) { } } ``` ---------------------------------------- TITLE: Defining Data Object with Collection Property - PHP DESCRIPTION: This code defines a basic `AlbumData` class extending the `Data` class. It includes a string property `title` and a `Collection` of `SongData` objects named `songs`. This example sets the foundation for later examples on controlling the inclusion of the `songs` collection. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/lazy-properties.md#_snippet_0 LANGUAGE: php CODE: ``` class AlbumData extends Data { /** * @param Collection $songs */ public function __construct( public string $title, public Collection $songs, ) { } } ``` ---------------------------------------- TITLE: Mapping property names with MapInputName attribute DESCRIPTION: Illustrates how to use the MapInputName attribute combined with SnakeCaseMapper to map camelCase property names in the data object to snake_case in the model. This allows seamless data transformation when property naming conventions differ. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/model-to-data-object.md#_snippet_4 LANGUAGE: PHP CODE: ``` use Spatie\LaravelData\Attributes\MapInputName; use Spatie\LaravelData\Mappers\SnakeCaseMapper; class ArtistData extends Data { public int $id; #[MapInputName(SnakeCaseMapper::class)] public string $fullName; public CarbonImmutable $created_at; public CarbonImmutable $updated_at; } ``` ---------------------------------------- TITLE: Instantiating a Data Object with Computed Properties (PHP) DESCRIPTION: Shows how to create an instance of the `SongData` class (which contains a computed property) using the static `from` method provided by `spatie/laravel-data`. The input array only needs to contain the source properties (`first_name`, `last_name`), and the computed property (`full_name`) will be automatically calculated during instantiation based on the logic defined in the class constructor. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/computed.md#_snippet_1 LANGUAGE: php CODE: ``` SongData::from(['first_name' => 'Ruben', 'last_name' => 'Van Assche']); ``` ---------------------------------------- TITLE: Loading relations on demand with LoadRelation attribute DESCRIPTION: Uses the LoadRelation attribute on a relation property to enable on-the-fly loading of that relation. When creating the data object, relations are loaded dynamically if they weren't preloaded with the model. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/model-to-data-object.md#_snippet_8 LANGUAGE: PHP CODE: ``` class ArtistData extends Data { public int $id; /** @var array */ #[LoadRelation] public array $songs; public CarbonImmutable $created_at; public CarbonImmutable $updated_at; } $artist = ArtistData::from(Artist::find(1)); ``` ---------------------------------------- TITLE: Converting Optional Values to Null in Laravel Data Objects in PHP DESCRIPTION: Shows how to configure a Data object to automatically convert Optional values to null using the withoutOptionalValues() factory method. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/optional-properties.md#_snippet_4 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, public Optional|null|string $artist, ) { } } SongData::factory() ->withoutOptionalValues() ->from(['title' => 'Never gonna give you up']); // artist will `null` instead of `Optional` ``` ---------------------------------------- TITLE: Using SnakeCaseMapper for All Properties in Laravel Data DESCRIPTION: Shows how to apply a snake_case mapping strategy to all properties in a Data object using the MapOutputName attribute with SnakeCaseMapper class. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/mapping-property-names.md#_snippet_2 LANGUAGE: php CODE: ``` #[MapOutputName(SnakeCaseMapper::class)] class ContractData extends Data { public function __construct( public string $name, public string $recordCompany, ) { } } ``` ---------------------------------------- TITLE: Returning a Data Collection in Controller (PHP) DESCRIPTION: Illustrates returning a collection of Laravel Data objects from a controller, which automatically transforms into a JSON array. `SongData::collect()` is used to create the collection from a collection of Song models retrieved via `Song::all()`. Requires Laravel Data and a Song model. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/from-data-to-resource.md#_snippet_2 LANGUAGE: php CODE: ``` SongData::collect(Song::all()); ``` ---------------------------------------- TITLE: Applying Max Validation Attribute DESCRIPTION: The `#[Max]` attribute validates that the input is less than or equal to a specified maximum value. The maximum value is provided as an argument. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/validation-attributes.md#_snippet_53 LANGUAGE: php CODE: ``` ```php #[Max(20)] public int $closure; ``` ``` ---------------------------------------- TITLE: Casting Collections to Laravel Collections - Laravel Data - PHP DESCRIPTION: Illustrates casting a given collection (such as an array) to a specific type, in this case a Laravel Collection, using the collect method's second parameter. The method returns a Laravel Collection of SongData objects. Transformation works only with non-paginator collections. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/collections.md#_snippet_4 LANGUAGE: php CODE: ``` SongData::collect($songs, Collection::class); // returns a Laravel collection of SongData objects ``` ---------------------------------------- TITLE: Using Custom collectArray Method to Return Custom Collection - Laravel Data - PHP DESCRIPTION: Utilizes the SongData::collectArray static method to create a SongCollection of SongData objects with unique artist tracking. Demonstrates how arrays of data can be collected into a specialized collection. Requires previously defined SongData and SongCollection classes. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/collections.md#_snippet_7 LANGUAGE: php CODE: ``` SongData::collectArray([ ['title' => 'Never Gonna Give You Up', 'artist' => 'Rick Astley'], ['title' => 'Living on a prayer', 'artist' => 'Bon Jovi'], ]); // returns an SongCollection of SongData objects ``` ---------------------------------------- TITLE: Creating a Collection of Data Objects in PHP DESCRIPTION: Demonstrates how to create a collection of Data objects from multiple model instances using the collect() static method on a Data class. This is useful for handling multiple records. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/from-data-to-array.md#_snippet_4 LANGUAGE: php CODE: ``` SongData::collect(Song::all()); ``` ---------------------------------------- TITLE: Casting Arrays or Collections of Non-Data Types in PHP DESCRIPTION: Defines how to cast iterable properties like arrays of DateTime objects using the 'cast_and_transform_iterables' feature, enabling strings in arrays to be transformed into DateTime instances during object creation. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/casts.md#_snippet_8 LANGUAGE: PHP CODE: ``` class ReleaseData extends Data { public string $title; /** @var array */ public array $releaseDates; } ``` ---------------------------------------- TITLE: Type-Hinting Spatie Data Collection with @var (PHP) DESCRIPTION: Alternatively, you can use a PHPDoc '@var' annotation directly above the property declaration to specify the type of elements in the collection. This example uses the full namespace for the SongData class within the annotation. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/nesting.md#_snippet_4 LANGUAGE: php CODE: ``` class AlbumData extends Data { public string $title; /** @var \App\Data\SongData[] */ public array $songs; } ``` ---------------------------------------- TITLE: Including Properties of a Lazy Data Object - PHP DESCRIPTION: This code demonstrates how to include properties of a lazy-loaded Data object. In this case, it includes the `name` property of the `favorite_song` within the `UserData` object. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/lazy-properties.md#_snippet_9 LANGUAGE: php CODE: ``` return UserData::from(Auth::user())->include('favorite_song.name'); ``` ---------------------------------------- TITLE: Adding Validation Attributes to Data Class Properties in Laravel Data DESCRIPTION: This snippet demonstrates using PHP attributes to add extra validation rules to specific properties within a Laravel Data class. In this example, the `#[Max(20)]` attribute is added to the `$artist` property, requiring that its string value does not exceed 20 characters. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_6 LANGUAGE: php CODE: ``` class SongData extends Data { public function __construct( public string $title, #[Max(20)] public string $artist, ) { } } ``` ---------------------------------------- TITLE: Using the all() Method to Transform Data Object in PHP DESCRIPTION: Demonstrates using the all() method to transform a Data object to an array without recursively transforming its properties. This is useful when you want to preserve complex property types. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/from-data-to-array.md#_snippet_2 LANGUAGE: php CODE: ``` SongData::from(Song::first())->all(); ``` ---------------------------------------- TITLE: Converting Data Object to JSON in PHP DESCRIPTION: Shows how to manually transform a Laravel Data object directly to a JSON string using the toJson() method. This is useful for API responses or other JSON output requirements. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/from-data-to-array.md#_snippet_3 LANGUAGE: php CODE: ``` SongData::from(Song::first())->toJson(); ``` ---------------------------------------- TITLE: Defining Expected Payloads for Nested Validation in Laravel Data (PHP) DESCRIPTION: This snippet provides an example of the nested array payload to be supplied for an AlbumData object containing multiple SongData instances. The payload includes album title and a songs array, where each song entry is an associative array representing its data. No dependencies are required to use this pattern. The structure matches the data object definitions for correct validation mapping. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/manual-rules.md#_snippet_7 LANGUAGE: php CODE: ``` [ 'title' => 'Best songs ever made', 'songs' => [ ['title' => 'Never Gonna Give You Up'], ['title' => 'Heroes', 'artist' => 'David Bowie'], ], ]; ``` ---------------------------------------- TITLE: Change Validation Strategy in Factory - Laravel Data DESCRIPTION: Demonstrates changing the validation strategy when creating data objects with a factory. `alwaysValidate()` enforces validation every time a data object is created. Alternatively, `withoutValidation()` disables validation completely, bypassing request validation. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/factories.md#_snippet_3 LANGUAGE: php CODE: ``` SongData::factory()->alwaysValidate()->from(['title' => 'Never gonna give you up', 'artist' => 'Rick Astley']); ``` LANGUAGE: php CODE: ``` SongData::factory()->withoutValidation()->from(['title' => 'Never gonna give you up', 'artist' => 'Rick Astley']); ``` ---------------------------------------- TITLE: Mapping Nested Properties with MapInputName in Laravel DESCRIPTION: This demonstrates how to map nested properties from an array to properties within a data object using dot notation within the `MapInputName` attribute. This allows accessing nested array values. Requires Spatie Laravel Data package. Input is an array with nested structure, and output is a `SongData` object. The dot notation allows access to nested array values. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/mapping-property-names.md#_snippet_5 LANGUAGE: php CODE: ``` use Spatie\LaravelData\Data; use Spatie\LaravelData\Attributes\MapInputName; class SongData extends Data { public function __construct( #[MapInputName("title.name")] public string $title, #[MapInputName("artists.0.name")] public string $artist ) { } } ``` ---------------------------------------- TITLE: Creating Data Object from Array PHP DESCRIPTION: Demonstrates creating an instance of a Data object using the static `from` method and an associative array as input. This method triggers the internal normalization process followed by the configured data pipeline (including `prepareForPipeline` if defined), hydrating the data object from the provided raw data. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/pipeline.md#_snippet_3 LANGUAGE: php CODE: ``` $songData = SongData::from([ 'title' => 'Never gonna give you up', 'release_year' => '1987', 'producer' => 'Stock Aitken Waterman', ]); ``` ---------------------------------------- TITLE: Creating a Basic Lazy Property - PHP DESCRIPTION: This snippet shows the basic way to create a lazy property. A closure which returns the value is passed to the Lazy::create method. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/lazy-properties.md#_snippet_10 LANGUAGE: php CODE: ``` Lazy::create(fn() => SongData::collect($album->songs)); ``` ---------------------------------------- TITLE: Generated Validation Rules with Default Values in Laravel Data DESCRIPTION: This snippet shows the validation rules generated for the `SongData` class when validating data that only provides the 'title' property, while 'artist' has a default value defined in the class. The 'required' rule is only generated for 'title' because 'artist' would be populated by its default if missing from the input. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_16 LANGUAGE: php CODE: ``` [ 'title' => ['required', 'string'], ] ``` ---------------------------------------- TITLE: PHP Data Object Class Structure for TypeScript Transformation DESCRIPTION: Defines a PHP class extending Data with various properties, demonstrating how a data object can be annotated and structured to be transformed into a TypeScript type by the package. The class includes properties with different types, including nullable, arrays, and union types, which will map to TypeScript definitions. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/typescript.md#_snippet_0 LANGUAGE: PHP CODE: ``` class DataObject extends Data { public function __construct( public null|int $nullable, public int $int, public bool $bool, public string $string, public float $float, /** @var string[] */ public array $array, public Lazy|string $lazy, public Optional|string $optional, public SimpleData $simpleData, /** @var \Spatie\LaravelData\Tests\Fakes\SimpleData[] */ public DataCollection $dataCollection, ) { } } ``` ---------------------------------------- TITLE: JSON Representation of a Data Collection (JSON) DESCRIPTION: Displays the JSON structure of a collection of SongData objects, showing an array of objects, each with "name" and "artist" properties. It demonstrates the format of a JSON array when a data collection is returned as a response. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/from-data-to-resource.md#_snippet_3 LANGUAGE: json CODE: ``` [ { "name": "Never Gonna Give You Up", "artist": "Rick Astley" }, { "name": "Giving Up on Love", "artist": "Rick Astley" } ] ``` ---------------------------------------- TITLE: Example Output of Retrieving Validation Rules for Laravel Data Object DESCRIPTION: This snippet shows the array structure returned by the `getValidationRules()` method for the `AlbumData` class (which contains a collection of `SongData` objects). The output includes rules for the parent properties and the nested collection items, demonstrating how rules are generated based on the data object structure. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/introduction.md#_snippet_20 LANGUAGE: php CODE: ``` [ 'title' => ['required', 'string'], 'songs' => ['required', 'array'], 'songs.*.title' => ['required', 'string'], 'songs.*.artist' => ['required', 'string'], ] ``` ---------------------------------------- TITLE: Filling Properties from Authenticated User DESCRIPTION: Shows how to use `FromAuthenticatedUser` to inject data from the authenticated user into a data object's property. It allows you to fill properties of the `SongData` object with user information. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-data-transfer-object/injecting-property-values.md#_snippet_7 LANGUAGE: php CODE: ``` class SongData extends Data { #[FromAuthenticatedUser] public UserData $user; } ``` ---------------------------------------- TITLE: Using the except() method with nested keys - PHP DESCRIPTION: This code shows how to use the except() method with nested keys. The data object will not show the 'songs.name' and 'songs.artist' properties. Note that this overwrites all other include and exclude statements. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/as-a-resource/lazy-properties.md#_snippet_23 LANGUAGE: php CODE: ``` AlbumData::from(Album::first())->except('songs.name', 'songs.artist'); ``` ---------------------------------------- TITLE: Implementing a Combined Cast and Transformer Class in PHP DESCRIPTION: Demonstrates how to create a single PHP class that implements both the `Cast` and `Transformer` interfaces from spatie/laravel-data. This allows the class (`ToUpperCastAndTransformer`) to handle both data creation casting (via `cast`) and data transformation (via `transform`), shown here by converting a string value to uppercase in both methods. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/creating-a-transformer.md#_snippet_1 LANGUAGE: php CODE: ``` use Spatie\LaravelData\Casts\Cast; use Spatie\LaravelData\Support\Creation\CreationContext; use Spatie\LaravelData\Support\DataProperty; use Spatie\LaravelData\Support\Transformation\TransformationContext; use Spatie\LaravelData\Transformers\Transformer; class ToUpperCastAndTransformer implements Cast, Transformer { public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): string { return strtoupper($value); } public function transform(DataProperty $property, mixed $value, TransformationContext $context): string { return strtoupper($value); } } ``` ---------------------------------------- TITLE: Overwriting validation error messages in Laravel Data class DESCRIPTION: Defines custom validation error messages by overriding the static messages() method in a PHP Data class, returning an array mapping validation rules to messages. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/working-with-the-validator.md#_snippet_0 LANGUAGE: PHP CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, ) { } public static function messages(): array { return [ 'title.required' => 'A title is required', 'artist.required' => 'An artist is required', ]; } } ``` ---------------------------------------- TITLE: Overwriting attribute names for validation in Laravel Data class DESCRIPTION: Overrides attribute names used in validation errors by implementing the static attributes() method, providing mappings from internal attribute names to user-friendly labels. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/working-with-the-validator.md#_snippet_1 LANGUAGE: PHP CODE: ``` class SongData extends Data { public function __construct( public string $title, public string $artist, ) { } public static function attributes(): array { return [ 'title' => 'titel', 'artist' => 'artiest', ]; } } ``` ---------------------------------------- TITLE: Data Object with Nullable Nested Data DESCRIPTION: This code shows an `AlbumData` object with a nullable `ArtistData` property. This allows the artist to be absent or null. The validation rules will change depending on the payload, whether a value for artist is provided or not. SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/validation/nesting-data.md#_snippet_4 LANGUAGE: php CODE: ``` class AlbumData extends Data { public function __construct( public string $title, public ?ArtistData $artist, ) { } } ``` ---------------------------------------- TITLE: Creating a Laravel Data Object with Mapped Properties (PHP) DESCRIPTION: This snippet demonstrates how to instantiate the `ContractData` object using its static `from` method. The input array provides keys corresponding to the mapping rules defined by the `#[MapName]` attributes in the `ContractData` class (e.g., 'record_company' maps to `$recordCompany`, 'CityName' maps to `$cityName`). SOURCE: https://github.com/spatie/laravel-data/blob/main/docs/advanced-usage/available-property-mappers.md#_snippet_1 LANGUAGE: php CODE: ``` ContractData::from([ 'name' => 'Rick Astley', 'record_company' => 'RCA Records', 'country field' => 'Belgium', 'CityName' => 'Antwerp', 'addressline1' => 'some address line 1', 'ADDRESSLINE2' => 'some address line 2', ]); ```