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

vandyczech's avatar

Add item to session array

I need store array with id in the session like this

Output for session()->all()['hidden']

1 , 2 , 3 , 4 , 5 ....

How can I add new id to the exist hidden array in session ?

0 likes
11 replies
edoc's avatar
session()->push('hidden', 'value');
Tray2's avatar
if($request->session()->get('id') == $id) {
    return redirect()->back();
}

session(['id' => $id]);

Should work for you

bobbybouwmann's avatar

You say it doesn't work, but I'm not sure what doesn't work for you. Can you be more specific here?

vandyczech's avatar

@bobbybouwmann How I said, i cant add new item to the array ... :// the item value (for this example ID) is overwritten still again ... I need create array hidden, add items to the array but in the session

when i store id 19, add to array('hidden') good
[hidden] => 19

when i store id 20, the value is overwritten .. :/
[hidden] => 20

but i need

[hidden]  => 19
          => 20
vandyczech's avatar

@BOBBYBOUWMANN - @bobbybouwmann I read this documentation, but push I use .. but doesnt work ..

My code

$hiddenArr = collect( session()->get('hidden') );
$hiddenArr->push($id);

if( $hiddenArr->contains($id) ){ 
            
 return redirect()->back(); 
        
 } 
        
else  {

session()->push('hidden',$id);
return redirect()->back();

}
bobbybouwmann's avatar

@vandyczech I think the problem might be that you don't start with an array at all, but with a single value. So you can try this instead

// Notice that we start with an array here and not a single value
session()->put('hidden', [19]);

session()->push('hidden', 20);

Can you confirm that this works for you?

bobbybouwmann's avatar

@vandyczech Well, it says that you can put anything in the session! Also it says this

The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so:

This assumes that you already have an array in the session and then you can push to it, otherwise it overrides it apparently.

Anyway if everything is working for you now you should mark it as the best answer because i've seen this question more often! It might help others ;)

Please or to participate in this conversation.