Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

panthro's avatar

DTOs and getting data from a database?

I understand DTOs and they are useful to keep data consistent.

All the examples I see use a DTO to transform data coming into an application from a request, but not data coming out of a database/model.

It got me thinking, should you use a DTO with data coming out of a database, surely the data is consistent as the source is known to you (as it is your database)?

0 likes
12 replies
Snapey's avatar

yes. Your database table should be in a known and consistent state, and there is no need to create a dto when you can pass an eloquent model around

1 like
panthro's avatar

@snapey great, so....

Data Out: Database -> Model -> ApiResource via Controller -> End User

Data In: Request -> Controller -> DTO (or a form request but a DTO maintains consistency if used elsewhere in the application) -> Model -> Database

Does this make sense?

Tray2's avatar

@panthro DTO is good in theory, and it makes sense in some cases, but when we are talking CRUD, there isn't really any need for it.

You have the $request and the eloquent model, those to could be considered as a kind of DTO. I suggest that you keep it simple and don't make any complex solution for simple crud.

1 like
Snapey's avatar

@panthro

Data In: Request -> FormRequest->Controller -> Model -> Database

In this regard, the form request class is ensuring the integrity of the data, no need for a DTO

1 like
panthro's avatar

@Snapey But what if I need to create a User from a command for example, how could I ensure the validity of the data as a form request is not used?

Tray2's avatar

@panthro Then you can extract the creation to a service class, or simply just push the logic of the creation into the model.

1 like
panthro's avatar

@Tray2 ah so perhaps create a repository to deal with the data between the controller and the model - then in here, have a validator?

Tray2's avatar

@panthro I hate the repository pattern, it just makes your code look like shit. Just let either the controller, or the model handle it, and use a form request to validate the data from the request.

1 like
panthro's avatar

@Tray2 but the data may not be coming from a request.

Regarding the repository pattern, if you have a complicated select, thats required in many controllers/files, would you repeat this code X times throughout your application? Where would you put it, im in that situation where i need a complex select throughout the application, so have just made a repository to deal with it.

Interested in your thoughts.

Snapey's avatar

@panthro

if you have a complicated select, thats required in many controllers/files, would you repeat this code X times throughout your application?

No, not repeat, I would build it into a scope.

1 like

Please or to participate in this conversation.