Reputation: 491
I have some fields in the form
<form action="users/registration/new_user" method="post" class="new_user" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-12 col-sm-12 col-xs-12 no-padding">
<div class="form-group col-md-2 col-sm-6 col-xs-12">
<label for="" class="dis-block">姓 <span class="text-error">※</span></label>
<input name="user_last_name" type="text" class="form-control" required="required">
</div>
<div class="form-group col-md-2 col-sm-6 col-xs-12">
<label for="" class="dis-block">名 <span class="text-error">※</span></label>
<input name="user_first_name" type="text" class="form-control" required="required">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 no-padding">
<div class="form-group col-md-4 col-sm-6 col-sm-6 col-xs-12 ch-width-100">
<label for="" class="dis-block">Email <span class="text-error">※</span></label>
<input name="user_email" type="email" class="form-control" required="required">
</div>
</div>
</form>
On my controller
public function postRegister(Request $request)
{
Session::put('user',['user_last_name'=>$request->user_last_name,'user_first_name'=>$request->user_first_name,'user_email'=>$request->user_email)]);
//Try echo to try it out
echo Session::get('user');
}
Error
ErrorException in SignupController.php line 146:
Array to string conversion
Now I have to do to save the array into the Session and when I need to call it can call the values by the foreach. Thanks everyone!
Upvotes: 2
Views: 4873
Reputation: 689
As for Laravel 8, session is not a class with static methods any longer, but a simple function in helpers.php that can get/set session values depending on the parameters specified. Also you can access the session through the request object, as stated at:
https://laravel.com/docs/8.x/session
Upvotes: 0
Reputation: 13259
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;
Upvotes: 2