Array & JSON Casting
For example, if your database has a JSON
or TEXT
field type that contains serialized JSON, adding the array
cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:
Open User.php model file and implement code as below
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'options' => 'array',
];
}
Once the cast is defined, you may access the options
attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options
attribute, the given array will automatically be serialized back into JSON for storage:
So, for example
Create Route in Web.php file as below
Route::get('/cast ', 'demoController@cast')->name('cast');
Create demoController
php artisan make:controller demoController -mcr
Open demoController.php in app\Http\Controller folder and implement code as below
public function cast()
{
$user = User::find(1);
$options = $user->options;
$options['key'] = 'value';
$user->options = $options;
$user->save();
}