John Davidson

php - Laravel - How to store multi objects in session

0 comments
Message:


Currently this is storing only first_name in session. I need to store some other objects of the selected user in session like level and city. How can I do that ?



+---------+----------+------------+-----------+-------+--------+
| id | username | first_name | last_name | level | city |
+---------+----------+------------+-----------+-------+--------+
| 1 | john | John | Parks | 1 | London |
| 2 | jack | Jack | Wilson | 2 | London |
| 3 | sam | Sam | Neil | 2 | London |
| 4 | bill | Bill | Paxton | 2 | London |
+---------+----------+------------+-----------+-------+--------+


DashboardContaroller.php



public function getIndex( Request $request )
{
$this->data['firstNames'] = \DB::table('tb_users')->orderBy('first_name')->lists('first_name', 'first_name');
Session::put('firstName', $request->get('first_name'));
return view('dashboard.index',$this->data);
}


index.blade.php



<form action="" method="post">
{!! Form::select('first_name', $firstNames) !!}
<button type="submit" value="Submit">Go</button>
</form>


View



<p>{{Session::get('firstName','default value')}}</p>


My Answer:
To store multiple objects in session, you can create an array and store it in the session. Here's how you can modify your code to store 'level' and 'city' along with 'first_name' in the session:

DashboardContaroller.php

public function getIndex( Request $request )
{
$selectedUser = \DB::table('tb_users')->where('first_name', $request->get('first_name'))->first();

$userData = [
'first_name' => $selectedUser->first_name,
'level' => $selectedUser->level,
'city' => $selectedUser->city
];

Session::put('userData', $userData);
return view('dashboard.index', $this->data);
}

index.blade.php


{!! Form::select('first_name', $firstNames) !!}



View

{{ Session::get('userData.first_name', 'default value') }}


{{ Session::get('userData.level', 'default value') }}


{{ Session::get('userData.city', 'default value') }}



Now, when a user selects a 'first_name' from the dropdown and submits the form, the 'level' and 'city' of the selected user will also be stored in the session. You can access these values in your views using Session::get('userData.level') and Session::get('userData.city').

Rate this post

4 of 5 based on 8494 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us