如何在 Session 上放置和检索 Laravel 集合对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32933717/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:26:37  来源:igfitidea点击:

how to put and retrieve laravel collection object on Session

laravellaravel-4laravel-5

提问by Sumit

I know that we can insert array in Session as Session::push('person.name','torres')but how to keep laravel collection object such as $product = Product::all();,as like Session::put('product',$product);.Ho wto achieve this?

我知道我们可以在 Session as 中插入数组,Session::push('person.name','torres')但是如何保留 laravel 集合对象,例如$product = Product::all();,as like 。Session::put('product',$product);如何实现这一点?

回答by ntzm

You can put any data inside the session, including objects. Seeing as a Collectionis just an object, you can do the same.

您可以将任何数据放入会话中,包括对象。将 a 视为一个Collection对象,您也可以这样做。

For example:

例如:

$products = Product::all();
Session::put('products', $products);
dd(Session::get('products'));

Should echo out the collection.

应该回显集合。

回答by Joseph Silber

You should convert it to a plain array, then convert them back to models:

您应该将其转换为普通数组,然后将它们转换回模型:

Storing in the session

存储在会话中

$products = Product::all()->map(function ($product) {
    return $product->getAttributes();
})->all();

Session::put('products', $products);

Retrieving from the session

从会话中检索

$products = Product::hydrate(Session::get('products'));


You can see an example of this method here.

您可以在此处查看此方法的示例。