php Laravel 在会话中存储数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37338526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Store Array in Session
提问by Nello
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.
有关如何创建存储一系列项目的购物车的任何线索和建议。
回答by mvpasarel
If you need to use the array from session as a string, you need to use Collection like this:
如果您需要将 session 中的数组用作字符串,则需要像这样使用 Collection:
$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.
这将使它在您将{{Session::get('cart');}}
在 html 中使用时起作用。请注意,Session::push
因为它会在会话中始终附加新产品。您应该使用Session::put
以确保产品将始终更新。
回答by Kirk Beard
You're storing an array in the session, and since {{ }}
expects a string, you can't use {{Session::get('cart')}}
to display the value.
您在会话中存储了一个数组,并且由于{{ }}
需要一个字符串,因此不能用于{{Session::get('cart')}}
显示该值。
The {{ $var }}
is the same as writing echo htmlentities($var)
(a very simple example).
这{{ $var }}
与写作相同echo htmlentities($var)
(一个非常简单的例子)。
Instead, you could do something like:
相反,您可以执行以下操作:
@foreach (Session::get('cart') as $product_id)
{{$product_id}}
@endforeach
回答by omarjebari
If you use 'push', when initially creating the array in the session, then the array will look like this:
如果使用“push”,在会话中最初创建数组时,数组将如下所示:
[
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);
回答by vinh hoang
You can use .
:
您可以使用.
:
$product = array(1,2,3,4);
Session::put('cart.product',$product);
回答by Faisal Mahmood
You can declare an array in session like
$cart = session('data', []);
您可以在会话中声明一个数组,例如
$cart = session('data', []);
$cart[] = $product;
session([ 'data' => $cart]);
return session('data', []);