### Install Laravel Validated DTO via Composer Source: https://context7.com/wendelladriel/laravel-validated-dto-docs/llms.txt This command installs the Laravel Validated DTO package using Composer, a dependency manager for PHP. Ensure Composer is installed and accessible in your project's root directory. ```bash composer require wendelladriel/laravel-validated-dto ``` -------------------------------- ### Configuration File Example Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/getting-started/configuration.md An example of the `validated-dto.php` configuration file. This file allows you to set the default namespace for your DTOs and configure the 'require_casting' option, which enforces explicit cast types for DTO properties. ```php 'App\\DTOs', /* |-------------------------------------------------------------------------- | REQUIRE CASTING |-------------------------------------------------------------------------- | | If this is set to true, you must configure a cast type for all properties of your DTOs. | If a property doesn't have a cast type configured it will throw a | \WendellAdriel\ValidatedDTO\Exceptions\MissingCastTypeException exception | */ 'require_casting' => false, ]; ``` -------------------------------- ### Implement SimpleDTO for Data Transformation Source: https://context7.com/wendelladriel/laravel-validated-dto-docs/llms.txt Provides an example of using SimpleDTO to handle data casting and property mapping without the overhead of validation. This is ideal for lightweight data objects that require transformation but not strict input checking. ```php class SimpleUserDTO extends SimpleDTO { public string $name; protected function mapData(): array { return ['username' => 'name']; } protected function casts(): array { return ['name' => new StringCast()]; } } $dto = SimpleUserDTO::fromArray(['username' => 'John Doe']); ``` -------------------------------- ### Install and Configure TypeScript Transformer Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/generating-typescript-definitions.md Install the necessary composer package and publish the configuration file to enable TypeScript generation for Laravel projects. ```bash composer require spatie/typescript-transformer php artisan vendor:publish --provider="Spatie\LaravelTypeScriptTransformer\TypeScriptTransformerServiceProvider" ``` -------------------------------- ### Configure Laravel Validated DTO Source: https://context7.com/wendelladriel/laravel-validated-dto-docs/llms.txt This is an example of the published configuration file (`config/dto.php`). It allows you to set the default namespace for your DTOs and enforce strict casting rules. ```php 'App\\DTOs', // If true, all properties must have a cast type configured // Throws MissingCastTypeException if a property lacks a cast type 'require_casting' => false, ]; ``` -------------------------------- ### Generate TypeScript Definitions for DTOs Source: https://context7.com/wendelladriel/laravel-validated-dto-docs/llms.txt Provides the configuration steps to export Laravel DTOs into TypeScript interfaces. This process involves installing the transformer package, updating the configuration file, and running the generation command. ```bash # Step 1: Install the required package composer require spatie/typescript-transformer # Step 2: Publish the config php artisan vendor:publish --provider="Spatie\LaravelTypeScriptTransformer\TypeScriptTransformerServiceProvider" ``` ```php [ Spatie\TypeScriptTransformer\Collectors\DefaultCollector::class, Spatie\TypeScriptTransformer\Collectors\EnumCollector::class, WendellAdriel\ValidatedDTO\Support\TypeScriptCollector::class, ], 'transformers' => [ Spatie\LaravelTypeScriptTransformer\Transformers\SpatieStateTransformer::class, Spatie\TypeScriptTransformer\Transformers\EnumTransformer::class, Spatie\TypeScriptTransformer\Transformers\SpatieEnumTransformer::class, Spatie\LaravelTypeScriptTransformer\Transformers\DtoTransformer::class, WendellAdriel\ValidatedDTO\Support\TypeScriptTransformer::class, ], ]; ``` ```bash # Step 4: Generate TypeScript definitions php artisan typescript:transform ``` -------------------------------- ### Automatic DTO Creation from Form Request in PHP Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/creating-dto-instances.md Explains how DTOs can be automatically instantiated when type-hinted as a Form Request in controller methods starting from v3. This streamlines controller logic by handling DTO creation implicitly. ```php public function store(UserDTO $dto): JsonResponse { // ... } ``` -------------------------------- ### Integrate Lazy DTO with Livewire (PHP) Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/lazy-validation.md Provides an example of creating a DTO that is compatible with Livewire's `Wireable` trait and also utilizes lazy validation. This combines the benefits of deferred validation with Livewire component integration. ```php use Livewire\Wireable as LivewireWireable; use WendellAdriel\ValidatedDTO\Concerns\Wireable; class MyDTO extends ValidatedDTO implements LivewireWireable { use Wireable; public bool $lazyValidation = true; } ``` -------------------------------- ### Define Validation Rules using rules() Method Source: https://context7.com/wendelladriel/laravel-validated-dto-docs/llms.txt This PHP example shows how to define validation rules for a `ValidatedDTO` using the `rules()` method. It supports standard Laravel validation rules, including the `Password` rules for secure password validation. ```php ['required', 'string'], 'email' => ['required', 'email'], 'password' => [ 'required', Password::min(8) ->mixedCase() ->letters() ->numbers() ->symbols() ->uncompromised(), ], ]; } } ``` -------------------------------- ### Configure Laravel Validated DTO settings Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/getting-started/upgrade-guide.md The updated configuration file allows developers to define the DTO namespace and enforce strict property casting. This file should be published or merged when upgrading to version 3. ```php 'App\\DTOs', /* |-------------------------------------------------------------------------- | REQUIRE CASTING |-------------------------------------------------------------------------- | | If this is set to true, you must configure a cast type for all properties of your DTOs. | If a property doesn't have a cast type configured it will throw a | \\WendellAdriel\\ValidatedDTO\\Exceptions\\MissingCastTypeException exception | */ 'require_casting' => false, ]; ``` -------------------------------- ### Utilize Built-in Type Casters for Complex Data Structures Source: https://context7.com/wendelladriel/laravel-validated-dto-docs/llms.txt Provides examples of various built-in casters available in ValidatedDTO, including support for collections, nested DTOs, Enums, and Eloquent Models. These casters handle complex data transformations and validation requirements. ```php ['required', 'string'], 'city' => ['required', 'string'], ]; } } class ComprehensiveDTO extends ValidatedDTO { protected function casts(): array { return [ 'tags' => new ArrayCast(), 'scores' => new ArrayCast(new IntegerCast()), 'is_active' => new BooleanCast(), 'price' => new FloatCast(), 'quantity' => new IntegerCast(), 'name' => new StringCast(), 'metadata' => new ObjectCast(), 'created_at' => new CarbonCast(), 'updated_at' => new CarbonCast('Europe/Lisbon'), 'published_at' => new CarbonCast('UTC', 'Y-m-d'), 'expires_at' => new CarbonImmutableCast(), 'items' => new CollectionCast(), 'users' => new CollectionCast(new DTOCast(AddressDTO::class)), 'address' => new DTOCast(AddressDTO::class), 'status' => new EnumCast(UserStatus::class), 'author' => new ModelCast(User::class), ]; } } ``` -------------------------------- ### Create DTO from Artisan Command Arguments and Options in PHP Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/creating-dto-instances.md Explains how to create a DTO instance using a combination of command-line arguments and options with the static `fromCommand` method. This offers flexibility in defining command inputs. ```php 'John Doe', 'email' => 'john.doe@example.com', 'password' => 's3CreT!@1a2B' ]); // From array (static method) $dto = UserDTO::fromArray([ 'name' => 'John Doe', 'email' => 'john.doe@example.com', 'password' => 's3CreT!@1a2B' ]); // From JSON string $dto = UserDTO::fromJson('{"name": "John Doe", "email": "john.doe@example.com", "password": "s3CreT!@1a2B"}'); // From Request object public function store(Request $request): JsonResponse { $dto = UserDTO::fromRequest($request); // Process the DTO... } // Type-hint injection (like Form Request) public function store(UserDTO $dto): JsonResponse { // DTO is automatically created from request return response()->json(['user' => $dto->toArray()]); } // From Eloquent Model (hidden fields are excluded) $user = User::find(1); $dto = UserDTO::fromModel($user); ``` -------------------------------- ### Create DTO from Artisan Command Options in PHP Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/creating-dto-instances.md Illustrates creating a DTO instance from command-line options using the static `fromCommandOptions` method. Options must be defined in the command's `$signature`. ```php info("User created: {$dto->name}"); } catch (ValidationException $e) { $this->error('Validation failed: ' . implode(', ', $e->errors())); return 1; } return 0; } } ``` -------------------------------- ### Create DTO from Artisan Command Arguments in PHP Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/creating-dto-instances.md Shows how to create a DTO instance from command-line arguments passed to an Artisan command using the static `fromCommandArguments` method. This requires defining arguments in the `$signature`. ```php 'John Doe', 'email' => 'john.doe@example.com', 'password' => 's3CreT!@1a2B' ]); ``` ```php $dto = UserDTO::fromArray([ 'name' => 'John Doe', 'email' => 'john.doe@example.com', 'password' => 's3CreT!@1a2B' ]); ``` -------------------------------- ### Generate SimpleDTO via Artisan Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/simple-dtos.md Use the Laravel Artisan command line interface to scaffold a new SimpleDTO class by passing the --simple flag. ```bash php artisan make:dto SimpleUserDTO --simple ``` -------------------------------- ### Publish Configuration File Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/getting-started/configuration.md This command publishes the configuration file for the Laravel Validated DTO package. It allows you to customize settings like the default namespace for your DTOs and whether casting is strictly required for all properties. ```bash php artisan vendor:publish --provider="WendellAdriel\ValidatedDTO\Providers\ValidatedDTOServiceProvider" --tag=config ``` -------------------------------- ### Publish DTO Stubs for Customization Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/generating-dtos.md This command publishes the DTO stub files to a `stubs` folder at the root of your project, allowing you to customize the structure and content of generated DTOs. ```bash php artisan dto:stubs ``` -------------------------------- ### Map DTO Properties on Instantiation (PHP) Source: https://context7.com/wendelladriel/laravel-validated-dto-docs/llms.txt Map incoming data property names to DTO property names using the mapData() method or the Map attribute. This is useful when request data keys differ from DTO property names. Supports nested data mapping and case conversion. ```php ['required', 'string'], 'email' => ['required', 'email'], ]; } protected function mapData(): array { return [ 'full_name' => 'name', // Maps incoming 'full_name' to 'name' ]; } } // Usage: request has 'full_name', DTO has 'name' $dto = UserDTO::fromArray(['full_name' => 'John Doe', 'email' => 'john@example.com']); echo $dto->name; // 'John Doe' // Using Map attribute class UserAttributeDTO extends ValidatedDTO { #[Map(data: 'full_name')] public string $name; public string $email; } // Mapping nested data to flat properties class NameDTO extends ValidatedDTO { public string $first_name; public string $last_name; protected function mapData(): array { return [ 'first_name' => 'name.first_name', 'last_name' => 'name.last_name', ]; } } // Input: ['name' => ['first_name' => 'John', 'last_name' => 'Doe']] // Result: $dto->first_name = 'John', $dto->last_name = 'Doe' // Using Receive attribute for case conversion #[Receive(PropertyCase::SnakeCase)] class CamelCaseDTO extends ValidatedDTO { public string $firstName; public string $lastName; } // Accept snake_case input, use camelCase properties $dto = new CamelCaseDTO(['first_name' => 'John', 'last_name' => 'Doe']); echo $dto->firstName; // 'John' ``` -------------------------------- ### Define a Resource DTO Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/resource-dtos.md Create a class extending ResourceDTO to define the structure of your API response. This class implements the Responsable interface, allowing it to be returned directly from controllers. ```php class UserResourceDTO extends ResourceDTO { public string $name; public string $email; public int $age; // Your DTO methods... } ``` -------------------------------- ### Generate TypeScript Definitions Source: https://github.com/wendelladriel/laravel-validated-dto-docs/blob/main/basics/generating-typescript-definitions.md Execute the artisan command to process the registered classes and generate the TypeScript definition file. ```bash php artisan typescript:transform ```