{"id":13563777,"url":"https://github.com/vkovic/laravel-custom-casts","last_synced_at":"2025-04-04T08:05:54.620Z","repository":{"id":44875874,"uuid":"160530104","full_name":"vkovic/laravel-custom-casts","owner":"vkovic","description":"Make your own custom cast type for Laravel model attributes","archived":false,"fork":false,"pushed_at":"2022-01-21T08:54:33.000Z","size":89,"stargazers_count":219,"open_issues_count":2,"forks_count":20,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-02T00:15:03.302Z","etag":null,"topics":["accessor","attribute","cast","casting","laravel","mutator","package"],"latest_commit_sha":null,"homepage":null,"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/vkovic.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-12-05T14:25:41.000Z","updated_at":"2024-06-22T06:40:46.000Z","dependencies_parsed_at":"2022-09-06T03:12:11.566Z","dependency_job_id":null,"html_url":"https://github.com/vkovic/laravel-custom-casts","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vkovic%2Flaravel-custom-casts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vkovic%2Flaravel-custom-casts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vkovic%2Flaravel-custom-casts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vkovic%2Flaravel-custom-casts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vkovic","download_url":"https://codeload.github.com/vkovic/laravel-custom-casts/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247142014,"owners_count":20890651,"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":["accessor","attribute","cast","casting","laravel","mutator","package"],"created_at":"2024-08-01T13:01:23.171Z","updated_at":"2025-04-04T08:05:54.602Z","avatar_url":"https://github.com/vkovic.png","language":"PHP","funding_links":[],"categories":["PHP"],"sub_categories":[],"readme":"# Laravel Custom Casts\n\n[![Build](https://api.travis-ci.org/vkovic/laravel-custom-casts.svg?branch=master)](https://travis-ci.org/vkovic/laravel-custom-casts)\n[![Downloads](https://poser.pugx.org/vkovic/laravel-custom-casts/downloads)](https://packagist.org/packages/vkovic/laravel-custom-casts)\n[![Stable](https://poser.pugx.org/vkovic/laravel-custom-casts/v/stable)](https://packagist.org/packages/vkovic/laravel-custom-casts)\n[![License](https://poser.pugx.org/vkovic/laravel-custom-casts/license)](https://packagist.org/packages/vkovic/laravel-custom-casts)\n\n### Make your own cast type for Laravel model attributes\n\nLaravel custom casts works similarly to [Eloquent attribute casting](https://laravel.com/docs/6.x/eloquent-mutators#attribute-casting), but with custom-defined logic (in a separate class). This means we can use the same casting logic across multiple models — we might write [image upload logic](https://github.com/vkovic/laravel-custom-casts/tree/v1.0.2#example-casting-user-image) and use it everywhere. In addition to casting to custom types, this package allows custom casts to listen and react to underlying model events.\n\nLet's review some Laravel common cast types and examples of their usage:\n\n```php\nnamespace App;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model\n{\n    protected $casts = [\n        'is_admin' =\u003e 'boolean',\n        'login_count' =\u003e 'integer'\n        'height' =\u003e 'decimal:2'\n    ];\n}\n```\n\nIn addition to `boolean`, `integer`, and `decimal`, out of the box Laravel supports `real`, `float`, `double`, `string`, `object`, `array`, `collection`, `date`, `datetime`, and `timestamp` casts.\n\nSometimes it is convenient to handle more complex types with custom logic, and for casts to be able to listen and react to model events. This is where this package come in handy.\n\n\u003eHandling events directly from custom casts can be very useful if, for example, we're storing an image using a custom casts and we need to delete it when the model is deleted. *Check out the [old documentation](https://github.com/vkovic/laravel-custom-casts/tree/v1.0.2#example-casting-user-image) for this example.*\n\n\n### :package: vkovic packages :package:\n\nPlease check out my other packages — they are all free, well-written, and some of them are useful :smile:. If you find something interesting, consider giving me a hand with package development, suggesting an idea or some kind of improvement, starring the repo if you like it, or simply check out the code - there's a lot of useful stuff under the hood.\n\n- [**vkovic/laravel-commando**](http://bit.ly/2GT7DV7) ~ Collection of useful `artisan` commands\n- *Coming soon* [**vkovic/laravel-event-log**](http://bit.ly/2MFtCn8) ~ Easily log and access logged events, optionally with additional data and the related model\n\n## Compatibility\n\nThe package is compatible with **Laravel** versions `5.5`, `5.6`, `5.7`, `5.8` and `6`\n\nand **Lumen** versions `5.5`, `5.6`, `5.7`, `5.8`.\n\nLaravel 7+ has native support for [Custom Casts](https://laravel.com/docs/7.x/eloquent-mutators#custom-casts) that are incompatible with this library.\n\nMinimum supported version of PHP is `7.1`. \nPHP `8` is also supported.\n\n## Installation\n\nInstall the package via Composer:\n\n```bash\ncomposer require vkovic/laravel-custom-casts\n```\n\n## Usage\n\n### Utilizing a custom cast class\n\nTo enable custom casts in a model, use the `HasCustomCasts` trait and define which attributes will be casted using `$casts` - per Laravel standards.\n\n```php\n// File: app/User.php\n\nnamespace App;\n\nuse App\\CustomCasts\\NameCast;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Vkovic\\LaravelCustomCasts\\HasCustomCasts;\n\nclass User extends Model\n{\n    use HasCustomCasts;\n\n    protected $casts = [\n        'is_admin' =\u003e 'boolean', // \u003c-- Laravel default cast type\n        'name' =\u003e NameCast::class // \u003c-- Our custom cast class (see the section below)\n    ];\n}\n```\n\n### Defining a custom cast class\n\nThis class will be responsible for our custom casting logic.\n\n```php\n// File: app/CustomCasts/NameCast.php\n\nnamespace App\\CustomCasts;\n\nuse Vkovic\\LaravelCustomCasts\\CustomCastBase;\n\nclass NameCast extends CustomCastBase\n{\n    public function setAttribute($value)\n    {\n        return ucwords($value);\n    }\n\n    public function castAttribute($value)\n    {\n        return $this-\u003egetTitle() . ' ' . $value;\n    }\n\n    protected function getTitle()\n    {\n        return ['Mr.', 'Mrs.', 'Ms.', 'Miss'][rand(0, 3)];\n    }\n}\n```\n\nThe required `setAttribute` method receives the `$value` being set on the model field, and should return a raw value to store in the database.\n\nThe optional `castAttribute` method receives the raw `$value` from the database, and should return a mutated value. If this method is omitted, the raw database value will be returned.\n\nFor the sake of this example we'll implement one more method which will attach a random title to a user when their name is retrieved from database.\n\n### Testing a custom cast class\n\nLet's create a user and see what happens.\n\n```php\n$user = new App\\User;\n$user-\u003ename = 'john doe';\n\n$user-\u003esave();\n```\n\nThis will create our new user and store their name in the database, with the first letter of each word uppercased.\n\nWhen we retrieve the user and try to access their name, title will be prepended to it — just like we defined in our custom `NameCast` class.\n\n```php\ndd($user-\u003ename); // 'Mr. John Doe'\n```\n\n### Handling model events\n\nLet's say that we want to notify our administrator when a user's name changes.\n\n```php\n// File: app/CustomCasts/NameCast.php\n\npublic function updated()\n{\n    $attribute = $this-\u003eattribute;\n\n    if($this-\u003emodel-\u003eisDirty($attribute)) {\n        // Notify admin about name change\n    }\n}\n```\n\nIn addition to the `updated` method, we can define other methods for standard model events:\n`retrieved`, `creating`, `created`, `updating`, `saving`, `saved`, `deleting`, `deleted`, `restoring` and `restored`.\n\n### Other functionality\n\nAs you can see from the above code, we can easily access the casted attribute name as well as an instance of the underlying model.\n\n```php\n// File: app/CustomCasts/NameCast.php\n\n// Get the name of the model attribute being casted\ndd($this-\u003eattribute); // 'name'\n\n// Access our `User` model\ndd(get_class($this-\u003emodel)); // 'App/User'\n```\n\nWe can also retrieve all casted attributes and their corresponding classes directly from the model.\n\n```php\n// File: app/User.php\n\ndd($this-\u003egetCustomCasts()); // ['name' =\u003e 'App/CustomCasts/NameCast']\n```\n\n### Using aliased casts\n\nYou may find it easier to use aliases for custom casts, e.g.:\n\n```php\nprotected $casts = [\n    'avatar' =\u003e 'image' // \u003c-- You prefer this ...\n    // ---\n    'avatar' =\u003e ImageCast::class // \u003c-- ... over this\n];\n```\n\nTo make the magic happen, first add the package's service provider to the `providers` array:\n\n```php\n// File: config/app.php\n\n'providers' =\u003e [\n    // ...\n\n    /*\n     * Package Service Providers...\n     */\n    Vkovic\\LaravelCustomCasts\\CustomCastsServiceProvider::class\n\n    // ...\n]\n```\n\nOnce the provider is added, publish the config file which will be used to associate aliases with their corresponding custom cast classes:\n\n```bash\nphp artisan vendor:publish --provider=\"Vkovic\\LaravelCustomCasts\\CustomCastsServiceProvider\"\n```\n\nThis command should create a config file located at `config/custom_casts.php`. Open it up and check out the comments for examples of config options.\n\n### Use it without Laravel\n\nThis package can also be used without full Laravel installation, with something like `jenssegers/model` or if your project \nis using `illuminate/database` library.\n\n\u003e #### More examples\n\u003e You can find more examples in the [old documentation](https://github.com/vkovic/laravel-custom-casts/tree/v1.0.2#example-casting-user-image).\n\n## Contributing\n\nIf you plan to modify this Laravel package you should run the tests that come with it.\nThe easiest way to accomplish this is with `Docker`, `docker-compose`, and `phpunit`.\n\nFirst, we need to initialize Docker container (see `docker-composer.yaml` for details).\n\n```bash\ndocker-compose up --exit-code-from app\n```\n\nAfter that, we can run tests and watch the output:\n\n```bash\ndocker-compose run --rm app phpunit\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvkovic%2Flaravel-custom-casts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvkovic%2Flaravel-custom-casts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvkovic%2Flaravel-custom-casts/lists"}