Sumit
Sumit

Reputation: 1325

how to put and retrieve laravel collection object on Session

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

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219936

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.

Upvotes: 5

ntzm
ntzm

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

Related Questions