Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Dto Laravel Package

open-southeners/laravel-dto

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require open-southeners/laravel-dto
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="OpenSoutheners\DataMapper\DataMapperServiceProvider"
    
  2. First Use Case: Define a DTO class (e.g., app/Dtos/UserDto.php):

    namespace App\Dtos;
    
    use OpenSoutheners\DataMapper\Dto;
    
    class UserDto extends Dto
    {
        public string $name;
        public int $age;
    }
    

    Map an Eloquent model to the DTO:

    use App\Models\User;
    use App\Dtos\UserDto;
    
    $user = User::find(1);
    $dto = UserDto::fromModel($user); // or `UserDto::fromArray($user->toArray())`
    
  3. Key Files to Review:

    • config/datamapper.php (for customization)
    • app/Dtos/ (DTO definitions)
    • app/Providers/DataMapperServiceProvider.php (if extending)

Implementation Patterns

Core Workflows

  1. DTO Creation:

    • From Models:
      $dto = UserDto::fromModel($user);
      
    • From Arrays:
      $dto = UserDto::fromArray($request->all());
      
    • Manual Instantiation:
      $dto = new UserDto();
      $dto->name = "John";
      $dto->age = 30;
      
  2. Validation: Use built-in validation rules or extend the DTO:

    class UserDto extends Dto
    {
        public string $email;
    
        public function rules(): array
        {
            return [
                'email' => 'required|email',
            ];
        }
    }
    
  3. Transformation: Convert DTOs back to arrays/models:

    $array = $dto->toArray();
    $model = User::fromDto($dto); // Requires custom `fromDto` method in model
    
  4. API Responses: Return DTOs directly in controllers:

    return response()->json(UserDto::fromModel($user));
    

Integration Tips

  • API Resources: Use DTOs alongside Laravel’s ApiResource for structured responses.
  • Form Requests: Validate incoming requests with DTOs:
    public function rules()
    {
        return (new UserDto())->rules();
    }
    
  • Service Layer: Pass DTOs between services for decoupled logic:
    $service->process(UserDto::fromModel($user));
    

Gotchas and Tips

Pitfalls

  1. Circular References:

    • Avoid infinite loops when mapping nested DTOs. Use ignoreMissing() or custom mappers:
      $dto = UserDto::fromModel($user)->ignoreMissing(['password']);
      
  2. Type Safety:

    • DTOs are loosely typed by default. Enforce types explicitly:
      class UserDto extends Dto
      {
          public function __construct(
              public string $name,
              public int $age
          ) {}
      }
      
  3. Performance:

    • Eager-load relationships before mapping to avoid N+1 queries:
      $user = User::with('posts')->find(1);
      $dto = UserDto::fromModel($user);
      

Debugging

  • Mapping Issues: Use dd($dto->getErrors()) to inspect validation errors.
  • Custom Logic: Override mapFromModel() or mapFromArray() for bespoke behavior:
    public function mapFromModel($model)
    {
        $this->name = strtoupper($model->name);
        return parent::mapFromModel($model);
    }
    

Extension Points

  1. Custom Mappers: Register custom mappers in config/datamapper.php:
    'mappers' => [
        'App\Dtos\UserDto' => \App\Mappers\UserMapper::class,
    ],
    
  2. DTO Events: Listen for DTO creation/modification:
    Dto::created(function ($dto) {
        // Log or process DTO
    });
    
  3. Testing: Use DtoTestCase for assertions:
    $this->assertDtoEquals($expectedDto, $actualDto);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours