是否可以在 Laravel 中将数组存储为闪存数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19777837/
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
Is it possible to store an array as flash data in Laravel?
提问by AntonNiklasson
I have been looking around for a way of doing this. I know it is possible to store an array in the session with the following: Session::push('user.teams', 'developers');
我一直在寻找一种方法来做到这一点。我知道可以使用以下内容在会话中存储数组:Session::push('user.teams', 'developers');
Is it possible to do the same but with flash data? Something like Session::flashpush('user.teams', array('developers', 'designers'));
would be great.
是否可以使用闪存数据执行相同操作?像Session::flashpush('user.teams', array('developers', 'designers'));
这样的东西会很棒。
The usecase for me at this moment is primarily the following:
目前我的用例主要如下:
Session::flash('flash_message', $validator->messages());
Session::flash('flash_message', $validator->messages());
回答by Israel Ortu?o
As far as I know, you can do it. I've checked this just in case:
据我所知,你可以做到。我已经检查过这个以防万一:
Session::flash('test', array('test1', 'test2', 'test3'));
... After the request
dd(Session::get('test'));
// array(2) { [0]=> string(5) "test1" [1]=> string(5) "test2" [2]=> string(5) "test3" }
It works. Also you can serialize an array or object as Christopher Morrissey just commented
有用。您也可以像 Christopher Morrissey 刚刚评论的那样序列化数组或对象
回答by conradkleinespel
I use this:
我用这个:
Session::flash($key, array_merge((array)Session::get($key), array($value)));
回答by mpen
I created this helper class:
我创建了这个助手类:
<?php
class Flash {
public static function push($key, $value) {
$values = Session::get($key, []);
$values[] = $value;
Session::flash($key, $values);
}
}
It allows you push multiple items to the same key such that it always return an array when fetched.
它允许您将多个项目推送到同一个键,以便在获取时始终返回一个数组。
Usage:
用法:
Flash::push('success','Feature saved');
Twig template (Blade shouldn't be too much different):
Twig 模板(Blade 应该不会有太大的不同):
{% if session_has('success') %}
<div class="alert alert-block alert-success fade in">
<button class="close" data-dismiss="alert">×</button>
{% for msg in session_get('success') %}
<p><i class="fa-fw fa fa-check"></i> {{ msg }}</p>
{% endfor %}
</div>
{% endif %}
In your scenario, you would probably use it like this:
在您的场景中,您可能会像这样使用它:
Flash::push('flash_message', 'user.teams');
Flash::push('flash_message', 'developers');