Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

masandikdev's avatar

Make Array Cookies on Laravel 5

Hi, i just want make array in cookies with laravel 5.

how to implement it.

**HomeController **

class HomeController extends Controller {
    public function sample1()
    {
        return dd( Cookie::get('name') );
    }

    public function sample2($id)
    {
        if (Cookie::get('name')) {
            $data   = array();
            $data[] = Cookie::get('name');
            array_push($data, $id);
        } else {
            $data   = $id;
        }

        $response = new Response('added');
        $response->withCookie(cookie('name', $data, 60));
        return $response;

    }

    public function sample3()
    {
        $cookie = Cookie::forget('name');
        $response = new Response('removed');
        $response->withCookie($cookie);
        return $response;
    }
}

what i got is

array:2 [▼
  0 => array:2 [▼
    0 => array:2 [▼
      0 => array:2 [▼
        0 => "1"
        1 => "2"
      ]
      1 => "3"
    ]
    1 => "4"
  ]
  1 => "5"
]

what i want is

[1, 2, 3, 4,  5] 
or
array [
0 => "1"
1 => "2"
3 => "3"
4 => "4"
5 => "5"
]

what i miss, please give me some advice or solution. thanks

0 likes
1 reply
adrian.nuernberger's avatar

@masandikdev you return a mixed value, which can be an array or int. so you have to check if the value from the cookie is an array or int.

quick and dirty:

public function sample2($id)
    {
        if ($cookie_data = Cookie::get('name')) {

            if(!is_array($cookie_data))
            {
                $data = [];
                $data[] = $cookie_data;
            }else{
                $data = $cookie_data;
            }
            
            array_push($data, $id);
        } else {
            $data   = $id;
        }

Please or to participate in this conversation.