Laravel Store Array in Session

Laravel Store Array in Session

If you need to use the array from session as a string, you need to use Collection like this:

$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.

How to store an array into a session and call it in Laravel?

When you do

Session::put('user', [...]);

It works. Your error comes from

echo Session::get('user');

You are trying to 'echo' an array. Replace it with

dd(Session::get('user'));
// or
print_r(Session::get('user'));

To use it in a foreach, you simply do

if ( Session::has('user')) {
foreach(Session::get('user') as $prop) {
echo $prop;
}
}

Update

The user you are saving is a simple array. But it seems you actually want an object. You should change the way you save it like this:

$user = (object) [
'user_last_name'=>$request->user_last_name,
'user_first_name'=>$request->user_first_name,
'user_email'=>$request->user_email
];

// or simply try like this
$user = (object) $request->all();

// or if you have a user Model
$user = new User($request->all());

Then save it in the session

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

Finally you can use it anywhere as an object

$user = Session::get('user');
echo $user->user_last_name;

Laravel - How to store array in session?

To save multiple data into session use :

public function getIndex( Request $request )
{

$this->data['firstNames'] = \DB::table('tb_users')->orderBy('first_name')->lists('first_name', 'id');
$user = User::where('id', '=', $request->get('id'))->get()->toArray();
Session::set('user', [ 'id' => $request->get('id'), 'last_name' => $request->get('last_name'), 'first_name' => $request->get('first_name'), ]);
return view('dashboard.index',['user'=>Session::get('user')]);
}

how to store array of data in Session and retrieve it Laravel?

You will have to use push here.

Session::push('product', $product);

So all new $product push into 'product' session variable.

How to push an array to an existing session in laravel

I suppose it can be something like:

// set products.name as array
session()->put('products.name', []);

// somewhere later
session()->push('products.name', $name1);

// somewhere else later
session()->push('products.name', $name2);

Unable to store array in session if array size is big laravel 6

Try using a different session driver.

Cookies have a maximum length of 4096 bytes - if you are currently using the cookie driver you may be bumping up against that limit.

.env:

SESSION_DRIVER=file

Laravel Cart session returns Object instead of Array, how can I convert the object to an array?

This may solve your problem;

$request->session()->get('cart')


Related Topics



Leave a reply



Submit