Tuesday, November 24, 2026SubscribeMastheadAbout
Cali ReporterCalifornia · National · West Coast · Good News

Advertisement

Technology

DTOs Replace Magic Arrays with Typed Data Objects in Laravel

This article explains how Data Transfer Objects (DTOs) can be used in Laravel to replace magic arrays with typed, immutable objects, improving code quality and reducing bugs.

Portrait of Benjamin Boyce
Artificial Intelligence & Technology · November 19, 2026
Share

AI-generated editorial illustration from an imagined camera angle.
AI-generated editorial illustration from an imagined camera angle. Source image: dev.to.

In Laravel, developers often use arrays to pass data between layers of the application. However, this approach can lead to issues such as runtime errors due to missing or incorrectly named keys. For example, a controller might receive a validated request and pass it to a service, which then attempts to access specific keys in the array. If a key is missing or renamed in the form request, it results in a runtime error instead of a compile-time error. DTOs address this problem by providing a typed, immutable object that carries data between layers of the application. This ensures that any missing or incorrect keys are caught at compile time rather than runtime. [1]

A DTO is an immutable, typed object that contains only data with names and types. It is not a model or a service, just data. PHP 8.1 introduced readonly properties, and PHP 8.2 introduced readonly classes, both of which prevent properties from being modified after construction. This immutability makes DTOs safe to pass around without worrying about side effects. For example, a final readonly class can be used to ensure that all properties are immutable, preventing any unintended changes to the data. [1]

To create a DTO from raw input, such as validated form data or API responses, a factory method called fromArray() can be used. This method handles the conversion from raw arrays, including type coercion and defaults. For instance, the fromArray() method can be used to convert a validated request into a DTO, ensuring that the data is properly typed and structured. This method is the only place in the codebase that deals with the messiness of raw arrays, making the rest of the code cleaner and more type-safe. [1]

DTOs are used for passing data between layers of the application, not for persistence. Eloquent models handle persistence, while DTOs are used for input and data transfer. For example, a DTO can be used as input to an action or service, and once the data is persisted, the Eloquent model takes over. DTOs can also be used for status checks, where a DTO carries the result of each health check, ensuring that the return type of the check is unambiguous and well-defined. [1]

Advertisement

The code examples provided are from the Laravel framework, specifically within a PHP 8.1+ environment. The DTO implementation discussed is part of a larger application structure, where controllers interact with services to process HTTP requests. The source material is from a Dev.to article, which is a community-driven platform for developers to share knowledge and tutorials. The article focuses on improving type safety and reducing runtime errors through the use of Data Transfer Objects (DTOs) in Laravel applications. The examples are drawn from a controller and service layer, illustrating the transition from using raw arrays to typed objects. The code is not tied to a specific real-world project but serves as a conceptual guide for Laravel developers aiming to refactor their code for better maintainability and clarity. [1]

The DTO implementation includes a `fromArray()` factory method, which is used to convert raw input data (such as validated form data or API responses) into strongly typed objects. This method is responsible for handling edge cases, such as missing keys, incorrect types, and default values. The `fromArray()` method is part of the DTO class and is the only place where raw array data is processed. This encapsulation ensures that the rest of the application can interact with typed objects without worrying about the underlying data structure. The method is explicitly defined in the `OrderCustomerData` class and includes type coercion and conditional logic to handle various input scenarios. [1]

The `WhmAccountData` DTO is used in a different context, where data is sourced from a WHM API webhook payload. This DTO includes multiple factory methods to accommodate different input sources, such as a validated form request, a WHM API payload, and an Eloquent model. These factory methods are named `fromRequest()`, `fromWhmPayload()`, and `fromCpanelAccount()`, respectively. Each method maps the keys from the input source to the DTO's properties, ensuring that the data is correctly transformed and typed. This approach allows the DTO to be reused across different parts of the application, even when the input structure varies. [1]

The article also discusses the distinction between DTOs and Eloquent models. DTOs are used for data transfer between application layers, such as from the HTTP layer to the service layer, whereas Eloquent models are used for interacting with the database. The `OrderCustomerData` DTO is used as input to an action or service, but once the data is persisted, the Eloquent `Order` model takes over. This separation ensures that DTOs are not used for persistence and that Eloquent models are not used for data transfer, which helps maintain a clean and organized application architecture. [1]

Advertisement

In the `neurax-host` project, DTOs are used for the status page, where the `ServiceCheckResult` DTO carries the result of each health check. This DTO is used in a health check implementation, such as the `DatabaseCheck` class, which implements the `StatusCheckInterface`. The `ServiceCheckResult` DTO is constructed with specific properties such as `name`, `icon`, `status`, `message`, and `responseTimeMs`. This DTO is used to provide a consistent and typed interface for the status check results, making it easier to handle and display these results in the application. The use of DTOs in this context ensures that the return type of the `run()` method is unambiguous and that the consuming code knows exactly what data to expect. [1]

Sources

Dev.to

Prepared with AI assistance from the cited sources.

The Cali Reporter newsletter

The stories worth your time.

California, the country, and what comes next. Join our free newsletter for reporting that keeps you informed.

By joining, you agree to receive the Cali Reporter newsletter. Unsubscribe at any time. Privacy policy.

More in Technology

  • Modern Web Guidance 1.0 and Browser Compatibility

    Modern Web Guidance 1.0, announced by Chrome for Developers on November 10, introduces browser compatibility data to assist coding agents in building web features. The initiative emphasizes the importance of fallback…

  • Apache mod_http2 Vulnerability Detection with Nmap

    A new Nmap scripting module has been developed to detect the Apache mod_http2 vulnerability (CVE-2026-119618), addressing the challenges of identifying affected systems accurately.

  • Securing Remote Vendor Access in Industrial Networks

    Best practices for managing remote vendor access in operational technology (OT) networks emphasize controlled access points, multifactor authentication, and time-bound sessions to reduce cybersecurity risks.

Advertisement