You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
### Make your own custom cast type for Laravel model attributes
8
+
### Make your own cast type for Laravel model attributes
9
9
10
-
Laravel custom casts works similarly to [Laravel default accessors and mutators](https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators),
11
-
but with one noticeable difference: we can take our casting/mutating logic (getters, setters) away from models and put it in separate class.
10
+
Laravel custom casts works similarly to [Laravel attribute casting](https://laravel.com/docs/5.8/eloquent-mutators#attribute-casting), but with our customly defined logic (in separated class). Beside casting to
11
+
our complex types this package gives us ability to listen and react to underlying model events.
12
12
13
-
For even more convenience our custom cast classes have ability to react to underlying model events.
13
+
Let's check out some common - Laravel default cast types and possible examples of their usage:
14
14
15
-
>For example, this could be very useful if we're storing image with custom casts and we need to delete it
16
-
>when model changes. See the [old documentation](https://github.com/vkovic/laravel-custom-casts/tree/v1.0.2#example-casting-user-image) for this examples.
15
+
```php
16
+
// File: app/User.php
17
17
18
-
### :package::package::package: ... Awesome new package ... :package::package::package:
18
+
namespace App;
19
19
20
-
As we're near 1000 downloads of `laravel-custom-casts`, I decided to create one more handy and useful package. It's collection of some neat Laravel `artisan` commands that I'm sure most of you will find useful.
20
+
use Illuminate\Database\Eloquent\Model;
21
21
22
-
Check it out: [vkovic/laravel-commando](https://github.com/vkovic/laravel-commando)
22
+
class User extends Model
23
+
{
24
+
protected $casts = [
25
+
'is_admin' => 'boolean',
26
+
'login_count' => 'integer'
27
+
'height' => 'decimal:2'
28
+
];
29
+
}
30
+
```
31
+
32
+
Beside `bolean`, `integer` and `decimal` from the example above, out of the box Laravel supports `real`, `float`, `double`, `string`, `object`, `array`, `collection`, `date`, `datetime`, and `timestamp` casts.
33
+
34
+
Sometimes it is convenient to handle more complex types with custom logic and ability to listen and react to model events. This is where this package come in handy.
>Handling events directly from custom casts could be very useful if we're, for e.g. storing image with custom casts and we need to delete it when the model gets deleted. *Checkout the [old documentation](https://github.com/vkovic/laravel-custom-casts/tree/v1.0.2#example-casting-user-image) for this example.*
0 commit comments