1. Go to this page and download the library: Download php-collective/laravel-dto library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
php-collective / laravel-dto example snippets
return [
'config_path' => config_path(), // Where DTO config files are located
'output_path' => app_path('Dto'), // Where to generate DTOs
'namespace' => 'App\\Dto', // Namespace for generated DTOs
'typescript_output_path' => resource_path('js/types'), // TypeScript output
'jsonschema_output_path' => resource_path('schemas'), // JSON Schema output
];
use PhpCollective\Dto\Builder\Dto;
use PhpCollective\Dto\Builder\Field;
use PhpCollective\Dto\Builder\Schema;
return Schema::create()
->dto(Dto::create('User')->fields(
Field::int('id'),
Field::string('name'),
Field::string('email')->nullable(),
))
->toArray();
use App\Dto\UserDto;
$user = new UserDto([
'id' => 1,
'name' => 'John Doe',
'email' => '[email protected]',
]);
return response()->json($user->toArray());
use App\Dto\ProfileDto;
use App\Dto\TagDto;
use PhpCollective\LaravelDto\Eloquent\DtoCast;
use PhpCollective\LaravelDto\Eloquent\DtoCollectionCast;
use PhpCollective\LaravelDto\Eloquent\HasDtoCasts;
class User extends Model
{
protected $casts = [
'profile' => DtoCast::class . ':' . ProfileDto::class,
'tags' => DtoCollectionCast::class . ':' . TagDto::class,
];
}
$user = User::firstOrFail();
$profile = $user->profile; // ProfileDto instance
$tags = $user->tags; // Collection<TagDto>|null
class User extends Model
{
use HasDtoCasts;
protected array $dtoCasts = [
'profile' => ProfileDto::class,
'tags' => [
'class' => TagDto::class,
'collection' => true,
],
];
}
use App\Dto\UserDto;
use PhpCollective\LaravelDto\Eloquent\CreatesDtoFromModel;
class User extends Model
{
use CreatesDtoFromModel;
protected function getDtoClass(): ?string
{
return UserDto::class;
}
}
$dto = $user->toDto();
use PhpCollective\LaravelDto\Eloquent\DtoModel;
class User extends DtoModel
{
protected function getDtoClass(): ?string
{
return UserDto::class;
}
}