jessarcher / laravel-castable-data-transfer-object

Automatically cast JSON columns to rich PHP objects in Laravel using Spatie's data-transfer-object class
https://jessarcher.com/blog/casting-json-columns-to-value-objects/
MIT License
328 stars 23 forks source link

Allow use DTO with default values when null database value #13

Closed daraghoshea closed 2 years ago

daraghoshea commented 2 years ago

Addresses issue #10 that identifies uses cases when you may want the cast object to instantiated even when the database value is null.

The current functionality in DataTransferObject's get() method is to return null automatically.

This PR introduces a nullable Cast Parameter that will ensure the Caster gets instantiated rather than return null. The nullable parameter was inspired by the Spatie Laravel Enum package that uses the same parameter, albeit for slightly different purposes.

The nullable parameter name can obviously be changed if preferred, just a suggestion.

I have a few use cases where this would be incredibly useful, particularly when working with Livewire, and running into issues using @entangle not having any (default) values.

First time pull request, but I had a look at the contributing guidelines and think I've covered them all. Let me know if I haven't.

daraghoshea commented 2 years ago

I also thought about PHP Attributes as a way to do this, but that would need to be defined with the Cast class, whereas the Cast Parameter provides the flexibility to use it with some model attributes and not others.

jessarcher commented 2 years ago

This looks great! Are you able to get that CI failure fixed then I'll merge :slightly_smiling_face:

daraghoshea commented 2 years ago

Great. Just applied a fix there 👍 .