Update April 25th, 2016: I don’t use Value Objects in Laravel anymore. Here’s why.
One idea of Value Objects is to restrict what a programmer can do within the model. For example, an EmailAddress value object cannot be set to an invalid email address.
The advantage is: Validation and consistency of the domain model.
With Laravel however, there are a few things to think about and it took me a while to figure out a good solution.
tl;dr:
- Use a Mutator to enforce the type of a Value Object
- Store your Value Object as native value in your Eloquent model
- Use an Accessor to create a Value Object from the native value
- Implement
__toString()
in your Value Object to allow toArray()
- Use the
JsonSerializable
interface to allow toJson()
conversion
- Plus: Do all of this automatically without Mutators and Accessors
Continue reading Value Objects in Laravel 5 with Eloquent Done Right