简体   繁体   中英

Laravel - How to store multi objects in session

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>

Your questions contains the answer also:

Session::put('firstName', $request->get('first_name'));

in the same way you can create another session:

Session::put('level', $request->get('level'));
Session::put('city', $request->get('city'));

Here you can insert an array:

$items = collect([
    [
        'firstname' => $request->get('first_name')
    ], [
        'firstname' => $request->get('first_name')
    ], [
        'firstname' => $request->get('first_name')
    ]
]);

foreach(Session::get('firstName') as $firstName) {
    $items[] = $firstName; //past the old items in the array.
}

Session::push('users', $items);

Now you can use:

<p>
    @foreach(Session::get('firstName',[]) as $users)
        {{ $user['firstname'] }}
    @endforeach
</p>

Hope this works!

To store data in the session, you will typically use the request instance's put method or the global session helper. Just send an array of data:

// Via a request instance...
$request->session()->put(['key1' => 'value1', 'key2' => 'value2']);

// Via the global "session" helper...
session(['key' => 'value', 'key2' => 'value2']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM