Reputation: 1325
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?
Upvotes: 5
Views: 12259
Reputation: 219936
You should convert it to a plain array, then convert them back to models:
$products = Product::all()->map(function ($product) {
return $product->getAttributes();
})->all();
Session::put('products', $products);
$products = Product::hydrate(Session::get('products'));
You can see an example of this method here.
Upvotes: 5
Reputation: 4821
You can put any data inside the session, including objects. Seeing as a Collection
is just an object, you can do the same.
For example:
$products = Product::all();
Session::put('products', $products);
dd(Session::get('products'));
Should echo out the collection.
Upvotes: 6