0

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);
}
2
  • 1
    what does the output of the json_decode statement look like? can you dump that or dd() it. Commented Mar 24, 2022 at 8:56
  • at the moment the column is completely empty, plus I'm calling the function using ajax and dumping doesn't work apparently(I've tried) @YasserSebai Commented Mar 24, 2022 at 9:19

2 Answers 2

3

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',
];
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

3 Comments

thanks, but it didn't work, still giving me a 500 internal server error, since I'm calling this in an ajax function
please dubug it, what is the error first line of 500
I already write to you, but my answer is not accepted. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.