Laravel Store Array in Session
You can use .
:
$product = array(1,2,3,4);
Session::put('cart.product',$product);
You're storing an array in the session, and since {{ }}
expects a string, you can't use {{Session::get('cart')}}
to display the value.
The {{ $var }}
is the same as writing echo htmlentities($var)
(a very simple example).
Instead, you could do something like:
@foreach (Session::get('cart') as $product_id)
{{$product_id}}
@endforeach
If you use 'push', when initially creating the array in the session, then the array will look like this:
[
0 => [1,2,3,4]
]
Instead you should use 'put':
$products = [1,2,3,4];
$request->session()->put('cart', $products);
Any subsequent values should be pushed onto the session array:
$request->session()->push('cart', 5);
If you need to use the array from session as a string, you need to use Collection like this:
$product = collect([1,2,3,4]);
Session::push('cart', $product);
This will make it work when you will be using {{Session::get('cart');}}
in your htmls. Be aware of Session::push
because it will append always the new products in sessions. You should be using Session::put
to be sure the products will be always updating.