{"id":16926313,"url":"https://github.com/jessarcher/laravel-castable-data-transfer-object","last_synced_at":"2025-03-02T06:08:06.221Z","repository":{"id":41195684,"uuid":"306241935","full_name":"jessarcher/laravel-castable-data-transfer-object","owner":"jessarcher","description":"Automatically cast JSON columns to rich PHP objects in Laravel using Spatie's data-transfer-object class","archived":false,"fork":false,"pushed_at":"2024-02-27T15:52:37.000Z","size":64,"stargazers_count":330,"open_issues_count":4,"forks_count":24,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-02-23T05:06:32.861Z","etag":null,"topics":["data-transfer-object","laravel","laravel-package","value-object"],"latest_commit_sha":null,"homepage":"https://jessarcher.com/blog/casting-json-columns-to-value-objects/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jessarcher.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-22T06:21:07.000Z","updated_at":"2025-02-20T15:11:39.000Z","dependencies_parsed_at":"2024-06-18T14:53:43.015Z","dependency_job_id":null,"html_url":"https://github.com/jessarcher/laravel-castable-data-transfer-object","commit_stats":{"total_commits":56,"total_committers":8,"mean_commits":7.0,"dds":0.4821428571428571,"last_synced_commit":"e3927fa2ddaff0861f990bceccc3e587294e0924"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jessarcher%2Flaravel-castable-data-transfer-object","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jessarcher%2Flaravel-castable-data-transfer-object/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jessarcher%2Flaravel-castable-data-transfer-object/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jessarcher%2Flaravel-castable-data-transfer-object/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jessarcher","download_url":"https://codeload.github.com/jessarcher/laravel-castable-data-transfer-object/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241465111,"owners_count":19967244,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-transfer-object","laravel","laravel-package","value-object"],"created_at":"2024-10-13T20:29:36.322Z","updated_at":"2025-03-02T06:08:06.196Z","avatar_url":"https://github.com/jessarcher.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Laravel Castable Data Transfer Object\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/jessarcher/laravel-castable-data-transfer-object.svg?style=flat-square)](https://packagist.org/packages/jessarcher/laravel-castable-data-transfer-object)\n[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/jessarcher/laravel-castable-data-transfer-object/run-tests?label=tests)](https://github.com/jessarcher/laravel-castable-data-transfer-object/actions?query=workflow%3Arun-tests+branch%3Amain)\n[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/jessarcher/laravel-castable-data-transfer-object/Check%20\u0026%20fix%20styling?label=code%20style)](https://github.com/jessarcher/laravel-castable-data-transfer-object/actions?query=workflow%3A\"Check+%26+fix+styling\"+branch%3Amain)\n[![Total Downloads](https://img.shields.io/packagist/dt/jessarcher/laravel-castable-data-transfer-object.svg?style=flat-square)](https://packagist.org/packages/jessarcher/laravel-castable-data-transfer-object)\n\nLaravel is awesome. Spatie's [data transfer object](https://github.com/spatie/data-transfer-object) package for PHP is awesome. They're already good friends, but now they're taking their relationship to the next level 💕\n\nHave you ever wanted to cast your JSON columns to a value object?\n\nThis package gives you an extended version of Spatie's `DataTransferObject` class, called `CastableDataTransferObject`.\n\nUnder the hood it implements Laravel's [`Castable` interface](https://laravel.com/docs/8.x/eloquent-mutators#castables) with a Laravel [custom cast](https://laravel.com/docs/8.x/eloquent-mutators#custom-casts) that handles serializing between the `DataTransferObject` (or a compatible array) and your JSON database column.\n\nFor an in-depth explanation of what it's actually doing and the motivation behind it, check out [the blog post that spawned it](https://jessarcher.com/blog/casting-json-columns-to-value-objects/).\n\nThis package has also been featured on [Laravel News](https://laravel-news.com/laravel-castable-data-transfer-object)!\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require jessarcher/laravel-castable-data-transfer-object\n```\n\n## Usage\n\n### 1. Create your `CastableDataTransferObject`\n\nCheck out the readme for Spatie's [data transfer object](https://github.com/spatie/data-transfer-object) package to find out more about what their `DataTransferObject` class can do.\n\n``` php\nnamespace App\\Values;\n\nuse JessArcher\\CastableDataTransferObject\\CastableDataTransferObject;\n\nclass Address extends CastableDataTransferObject\n{\n    public string $street;\n    public string $suburb;\n    public string $state;\n}\n```\n\n(Note: I like to put these in `App\\Values` because I'm using them as a value object and not just a plain DTO. Feel free to put it anywhere you like!)\n\n### 2. Configure your Eloquent attribute to cast to it:\n\nNote that this should be a `jsonb` or `json` column in your database schema.\n\n```php\nnamespace App\\Models;\n\nuse App\\Values\\Address;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model\n{\n    protected $casts = [\n        'address' =\u003e Address::class,\n    ];\n}\n```\n\nAnd that's it! You can now pass either an instance of your `Address` class, or even just an array with a compatible structure. It will automatically be cast between your class and JSON for storage and the data will be validated on the way in and out.\n\n```php\n$user = User::create([\n    // ...\n    'address' =\u003e [\n        'street' =\u003e '1640 Riverside Drive',\n        'suburb' =\u003e 'Hill Valley',\n        'state' =\u003e 'California',\n    ],\n])\n\n$residents = User::where('address-\u003esuburb', 'Hill Valley')-\u003eget();\n```\n\nBut the best part is that you can decorate your class with domain-specific methods to turn it into a powerful value object.\n\n```php\n$user-\u003eaddress-\u003etoMapUrl();\n\n$user-\u003eaddress-\u003egetCoordinates();\n\n$user-\u003eaddress-\u003egetPostageCost($sender);\n\n$user-\u003eaddress-\u003ecalculateDistance($otherUser-\u003eaddress);\n\necho (string) $user-\u003eaddress;\n```\n\n\n### Using defaults for null database values\n\nBy default, if a database value is `null`, then the model attribute will also be `null`. However, sometimes you might want to instantiate the attribute with some default values.\n\nTo achieve this, you may provide an additional `nullable` [Cast Parameter](https://laravel.com/docs/eloquent-mutators#cast-parameters) to ensure the caster gets instantiated.\n\n```php\nnamespace App\\Models;\n\nuse App\\Values\\Address;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model\n{\n    protected $casts = [\n        'settings' =\u003e Settings::class . ':nullable',\n    ];\n}\n```\n\nThis will ensure that the `Settings` caster is instantiated even when the `settings` column in the database is `null`.\n\nYou may then specify some default values in the cast which will be used instead.\n\n```php\nuse JessArcher\\CastableDataTransferObject\\CastableDataTransferObject;\n\nclass Settings extends CastableDataTransferObject \n{\n    public string $title = 'Default';\n}\n```\n\n### Controlling serialization\n\nYou may provide the caster with flags to be used for serialization by adding the `CastUsingJsonFlags` attribute to your object:\n\n```php\nuse JessArcher\\CastableDataTransferObject\\CastableDataTransferObject;\nuse JessArcher\\CastableDataTransferObject\\CastUsingJsonFlags;\n\n#[CastUsingJsonFlags(encode: JSON_PRESERVE_ZERO_FRACTION)]\nclass Address extends CastableDataTransferObject {}\n```\n\n### Testing\n\n``` bash\ncomposer test\n```\n\n### Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n### Security\n\nIf you discover any security related issues, please email jess@jessarcher.com instead of using the issue tracker.\n\n## Credits\n\n- [Jess Archer](https://github.com/jessarcher)\n- [Jeremiasz Major](https://github.com/jrmajor)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n\n## Laravel Package Boilerplate\n\nThis package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjessarcher%2Flaravel-castable-data-transfer-object","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjessarcher%2Flaravel-castable-data-transfer-object","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjessarcher%2Flaravel-castable-data-transfer-object/lists"}