2016-12-22 54 views
2

當前,這僅在會話中存儲first_name。我需要在會話級別和城市中存儲選定用戶的其他對象。我怎樣才能做到這一點 ?Laravel - 如何在會話中存儲多個對象

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

我建議在會話中存儲大量的數據。我不建議存儲整個用戶對象,而是建議存儲用戶標識並從數據庫中提取用戶對象。 – GordonM

+0

我同意@GordonM你能告訴我的方式 – Selim

+0

只需將用戶ID(用戶表中的ID的值)存儲起來,並在需要詳細信息時使用它查看數據庫中的用戶 – GordonM

回答

2

您的問題包含答案也:

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

我想他想做出多個項目的數組... –

+0

是的,我需要一個數組@Robin – Selim

+0

@Selim看到我的答案,希望工程! –

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

現在你

Session::put('firstName', $request->get('first_name')); 
你可以創建另一個會話那樣

可以使用:

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

希望這個作品!

+0

謝謝。我得到錯誤**未定義的變量:用戶** – Selim

+0

我想你只有'firstname'從請求,如果你有'user_id'你可以得到用戶對象,並在數組中! @Selim –

+0

現在得到這個錯誤**提供給foreach()的無效參數** – Selim