16

I have been having trouble storing an array in session. I am making a shopping cart and it doesn't seem to work.

public function __construct(){

  $product = array(1,2,3,4);
  Session::push('cart', $product);

}

and then retrieve it in the view like this.

{{Session::get('cart')}}

However I keep getting an error like this.

htmlentities() expects parameter 1 to be string, array given

Any clues and advice on how to create a shopping cart that stores an array of items.

Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
Nello
  • 1,737
  • 3
  • 17
  • 24

6 Answers6

25

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.

mvpasarel
  • 775
  • 5
  • 13
8

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
Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
  • I was curious why does collections or $request->all() can be used through {{ }} ? Don't htmlentities goes through them too? – Nello May 20 '16 at 05:44
  • 1
    @Nello Collections provides a wrapper for working with arrays. If you attempt to `echo $collection` or use `{{ $collection }}`, the Collection handles this automatically using a [`__toString()`](https://github.com/laravel/framework/blob/5.2/src/Illuminate/Support/Collection.php#L1138-L1146) method. The `$request->all()` would be handled as a Collection, rather than a normal array. – Kirk Beard May 20 '16 at 07:02
5

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);
omarjebari
  • 4,861
  • 3
  • 34
  • 32
3

You can use .:

$product = array(1,2,3,4);
Session::put('cart.product',$product);
double-beep
  • 5,031
  • 17
  • 33
  • 41
vinh hoang
  • 39
  • 2
0

You can declare an array in session like $cart = session('data', []);

$cart[] = $product;

session([ 'data' => $cart]);

return session('data', []);
0

you can also do it like that:

  $data = collect($Array); 
  Session()->put('data', $data);
  return view('pagename');