Laravel - 如何在会话中存储多个对象

时间:2016-12-22 08:58:04

标签: php laravel

目前,这只是在会话中存储first_name。我需要在会话中存储所选用户的一些其他对象,如级别和城市。我怎么能这样做?

+---------+----------+------------+-----------+-------+--------+
|    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>

查看

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

2 个答案:

答案 0 :(得分:2)

您的问题也包含答案:

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

与创建另一个会话的方式相同:

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

答案 1 :(得分:1)

您可以在此处插入数组:

$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);

现在你可以使用:

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

希望这有效!