session()->push('hidden', 'value');
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 ?
if($request->session()->get('id') == $id) {
return redirect()->back();
}
session(['id' => $id]);
Should work for you
@TRAY2 - But I have value in the array ..
['hidden'] => 0 => 16 1 => 17
You say it doesn't work, but I'm not sure what doesn't work for you. Can you be more specific here?
@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
According to the docs this should work just fine!
Documentation: https://laravel.com/docs/5.8/session#storing-data
@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();
}
@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 - Works fine, thank you .. but there is no mention in the documentation that I could use [ $id ]
@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.