Trying to save a javascript cookie to the database

I set the cookie using javascript in my view like this:

<script>
    var draggable_array = ['drag1','drag2'];
    draggable_array.push('draggable3');
    var json_str = JSON.stringify(draggable_array);
    document.cookie = 'drags' + "=" + json_str;
    </script>

And in the view, I’ve tried two different methods to view my cookie. I can just use regular PHP like this:

    <?php
    print_r($_COOKIE['drags']);
    ?>

Or I can set the draggables in the controller like this

$this->set('foo', $this->request->getCookie('drags'));

I can see the cookie in my view when I do this:

echo $foo;

It prints out:

["drag1","drag2","draggable3"]

But when I set the variable to be used in the controller like this:

$draggables = $this->request->getCookie('drags');

and then I try to add it to my draggables field in the mealplans table like this:

    if ($this->request->is('post')) {
    $mealplan = $this->Mealplans->patchEntity($mealplan, $this->request->getData());
    if ($this->Mealplans->save($mealplan)) {
    $mealplan->draggables = $draggables;

it doesn’t save it to the table. It’s an empty string.

I am using cakephp version 4.

Never mind, I just changed the order of the commands and now it works.

if ($this->request->is('post')) {

		$mealplan = $this->Mealplans->patchEntity($mealplan, $this->request->getData());
		
		$mealplan->draggables = $draggables;
		
            if ($this->Mealplans->save($mealplan)) {

Yep, setting something that you want to save, after you’ve done the save, isn’t going to be helpful.