1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6
7class User extends Model
8{
9 /**
10 * The attributes that should be cast.
11 *
12 * @var array
13 */
14 protected $casts = [
15 'options' => 'array',
16 ];
17}
1To define a mutator, define a setFooAttribute method on your model where Foo
2 is the "studly" cased name of the column you wish to access. So, again,
3lets define a mutator for the first_name attribute. This mutator will
4be automatically called when we attempt to set the value of the first_name
5attribute on the model:
6
7class User extends Model
8{
9 public function setFirstNameAttribute($value)
10 {
11 $this->attributes['first_name'] = strtolower($value);
12 }
13}
1Once the cast is defined, you may access
2 the options attribute and
3 it will automatically be deserialized
4 from JSON into a PHP array. When you set
5 the value of the options attribute, the given
6 array will automatically be serialized back into
7 JSON for storage:
8
9
10use App\Models\User;
11
12$user = User::find(1);
13
14$options = $user->options;
15
16$options['key'] = 'value';
17
18$user->options = $options;
19
20$user->save();