Home > OS >  store and update an array as json in mysql database laravel 9
store and update an array as json in mysql database laravel 9

Time:03-24

I have values that I want to store in the database, I have declared the type as json and cast it as an array:

    protected $casts = [
    'favourites' => 'array'
];

however, I'm not sure how to add and update and read the values inside, any ideas? controller function:

public function addtofav()
{
    $id = request()->get('id');
    $user = auth()->user();
    json_decode($user->favourites,true);
    array_push($user->favourites,$id);
    dump('hello');
    json_encode($user->favourites);
    $user->save();
    return response(['id'=> $id],200);
}

CodePudding user response:

Quoting from the Laravel documenations:

adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model.

therefore, no need to make any encoding or decoding to your values before any update or create, just keep it as an array and Eloquent will take care of that, since you have the $cast array as below:

protected $casts = [
    'options' => 'array',
];

CodePudding user response:

Actually you should use many to many but if you want to use array, you don't encode or decode.

public function addtofav()
{
    $id = request()->get('id');
    $user = auth()->user();
    $favourites = $user->favourites;
    array_push($favourites,$id);
    $user->favourites = $favourites
    $user->save();
    return response(['id'=> $id],200);
}
  • Related