@@ -49,6 +49,30 @@ composer require vkovic/laravel-custom-casts
4949
5050## Usage
5151
52+ ### Utilizing a custom casts class
53+
54+ To enable custom casts in our models, we need to use ` HasCustomCasts ` trait and we need to define which filed will be casted - per Laravel standards.
55+
56+ ``` php
57+ // File: app/User.php
58+
59+ namespace App;
60+
61+ use App\CustomCasts\NameCast;
62+ use Illuminate\Database\Eloquent\Model;
63+ use Vkovic\LaravelCustomCasts\HasCustomCasts;
64+
65+ class User extends Model
66+ {
67+ use HasCustomCasts;
68+
69+ protected $casts = [
70+ 'is_admin' => boolean // <-- Laravel default cast type
71+ ' name' => NameCast::class // <-- Our custom cast class (follow section below)
72+ ];
73+ }
74+ ```
75+
5276### Defining custom cast class
5377
5478This class will be responsible for our custom casting logic.
@@ -86,31 +110,9 @@ Optional `getAttribute` method receives raw `$value` from database and should re
86110For the sake of this example we'll implement one more method which will attach random title to our users
87111when name is returned from database.
88112
89- ### Utilizing our custom casts class
90-
91- To enable custom casts in our models, we need to use ` HasCustomCasts ` trait.
92- Beside that, we need to define which filed will use our custom cast (in this case ` NameCast ` class), following standard Laravel approach.
93-
94- ``` php
95- // File: app/User.php
96-
97- namespace App;
98-
99- use App\CustomCasts\NameCast;
100- use Illuminate\Database\Eloquent\Model;
101- use Vkovic\LaravelCustomCasts\HasCustomCasts;
102-
103- class User extends Model
104- {
105- use HasCustomCasts;
106-
107- protected $casts = [
108- 'name' => NameCast::class // <-- Our custom cast class from above
109- ];
110- }
111- ```
113+ ### Let's test it
112114
113- Lets create example user and see what ' s happening .
115+ Let's create a user and see what will happen .
114116
115117``` php
116118$user = new App\User;
@@ -122,15 +124,15 @@ $user->save();
122124This will create our new user and his name will be stored in the database, first letters uppercased.
123125
124126When we retrieve our user and try to get his name, title will be prepended to it, just like we defined it
125- in `NameCast` class.
127+ in our custom ` NameCast ` class.
126128
127129``` php
128130dd($user->name); // 'Mr. John Doe'
129131```
130132
131133### Handling model events
132134
133- Lets say that we want to notify our administrator when user name changes.
135+ Let's say that we want to notify our administrator when user name changes.
134136
135137``` php
136138// File: app/CustomCasts/NameCast.php
0 commit comments