Custom Eloquent Casts &amp; Value Objects in Laravel | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Contextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms        On this page       1. [  Why Built-in Casts Stop Being Enough ](#why-built-in-casts-stop-being-enough)
2. [  Anatomy of a Custom Cast Class ](#anatomy-of-a-custom-cast-class)
3. [  Inbound-Only Casts ](#inbound-only-casts)
4. [  Hydrating Composite Value Objects ](#hydrating-composite-value-objects)
5. [  Testing Cast Classes in Isolation ](#testing-cast-classes-in-isolation)
6. [  Takeaways ](#takeaways)

  ![Contextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms](https://cdn.msaied.com/552/a7825c0c6f53d934f84fce522573eafb.png)

  #laravel   #eloquent   #value-objects   #casts   #php  

 Contextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms 
============================================================================================

     15 Aug 2026      1 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

1. [  01   Why Built-in Casts Stop Being Enough  ](#why-built-in-casts-stop-being-enough)
2. [  02   Anatomy of a Custom Cast Class  ](#anatomy-of-a-custom-cast-class)
3. [  03   Inbound-Only Casts  ](#inbound-only-casts)
4. [  04   Hydrating Composite Value Objects  ](#hydrating-composite-value-objects)
5. [  05   Testing Cast Classes in Isolation  ](#testing-cast-classes-in-isolation)
6. [  06   Takeaways  ](#takeaways)

 Why Built-in Casts Stop Being Enough
------------------------------------

Laravel ships with a solid set of primitive casts — `integer`, `boolean`, `encrypted`, `AsCollection`, and friends. They cover 80% of daily work. The remaining 20% is where bugs hide: money stored as integers but displayed as decimals, coordinates serialised as JSON but consumed as typed objects, or phone numbers that must be normalised on write and formatted on read.

Custom cast classes solve all three cases without polluting model methods or observers.

---

Anatomy of a Custom Cast Class
------------------------------

A cast class implements `CastsAttributes`. The two methods are `get` (hydrate from DB) and `set` (dehydrate to DB).

```php
