How to store associative array in session variable I want to store an associative array in session variable.
The structure should be like-
'arrayname'
9 => int 1
11 => int 2
Any help please??
HI,
Try this:
$array = ["9"=> 1, "11"=>2];
set it on session with: session($array);
Use below code to array in session variable.
Session::push('arrayName', [
'9' => 1,
'11' => 2
]);
Hope, this work for you !
@saurabhd This creates a nested array that I don't want..
Simple Solution that works always for me :
$request->session()->push('session_detail', [
'id' => 1,
'name' => 'Catalyst'
]);
Getting the detail:
request()->session()->get('session_detail')
@proelitesunny I am also facing the same.. I want to store details about the user as a single dimentional array in the sesssion.
I tried with @peacengara solution and when I try to access the session_detail using $request->session()->get('session_detail'); it return me below output
Array
(
[0] => Array
(
[id] => 1
[name] => Catalyst
)
[1] => Array
(
[id] => 1
[name] => Catalyst
)
[2] => Array
(
[id] => 1
[name] => Catalyst
)
)
I am looking for output as below
Array
(
[id] => 1
[name] => Catalyst
)
If you use 'push', when initially creating the array in the session, then the array will look like this only:
Array
(
[0] => Array
(
[id] => 1
[name] => Catalyst
)
)
Instead you should use 'put':
$request->session()->put('session_detail', ["id"=>1,"name"=>"Catalyst"]);
This will print
Array
(
[id] => 1
[name] => Catalyst
)
thanks @RamjithAp for the solution. Alternatively I found another way to implement this using global helper method session()
set the session like this
session(['user' => [
'id'=> $id,
'name'=> 'Manny'
]]);
And access the details like this.
$user_details = session('user');
print_r($user_details);
please how can i get id alone , and name alone ??
Please sign in or create an account to participate in this conversation.