Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

php - Laravel Store Array in Session

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...