Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Premium Members Only
Join to unlock this tutorial and all of our courses.
Tutorial Premium Tutorial

DTO: Value Objects and Data (Transfer) Objects in Laravel

December 01, 2022
9 min read

Historically, PHP has been a "loosely typed" language, with auto-converting between strings/integers and potential "magic" or bugs because of that. Slowly, the language itself evolved with type-hinting and return types, but also more people started to create their own object types, to define their object rules for minimizing bugs. These are called VALUE OBJECTS, and in this article, we'll cover when/how to use them.


When/Why You Need a Value Object?

A quick answer would be this: you need to define the rules for the variable behavior, so if those rules are broken, PHP would throw an exception.

General string/integer/boolean variable types are often too broad to define a real-life complex business logic of the applications.

I really recommend watching the talk by Kai Sassnowski at the recent Laracon Online, where he presented three real-life examples of creating specific classes instead of integer/float/string variables.

In summary, those examples are:

  • Parameter $seconds is not just an integer, it's a positive integer, so it's an object of class Duration that implements the validation of positive number;
  • Parameter $discount is not just a float, it's a float between 0.01 and 1, so it's an object of class Discount that implements the necessary validation;
  • Parameter $deviceID is not just a string UUID, it's a device with its unique validation rules, so it's an object of class DeviceID with the validation.

So, instead of...

Premium Members Only

This advanced tutorial is available exclusively to Laravel Daily Premium members.

Premium membership includes:

Access to all premium tutorials
Video and Text Courses
Private Discord Channel

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.