我应该在Laravel 5的会话变量中存储哪些数据
我是laravel的新手.我一直在与不同类型的用户一起开发laravel 5应用程序.我需要有关视图的不同部分中当前登录的用户类型的信息:
I am new to laravel. I have been working on a laravel 5 app with different types of users. I need information about which type of user is currently logged in different sections of my views:
目前,我已经在下面的各种控制器方法上进行了类似的操作,并且使用了user对象,我可以确定它在我看来是哪种类型的用户:
Currently, I have been doing something like below on various controller methods and with the user object, I can determine which type of user it is in my view:
在控制器中:
public function someMethod(){
$user = Auth::user();
return view('applications.show', compact('user'));
}
在视图中:
if($user->is_manager)
// do this
else if($user->is_admin)
// do that
因为我需要各种视图中有关用户类型的信息,所以我已经在多个地方调用了Auth::user()
,并且我开始认为这会增加数据库的负担.将用户类型存储在会话变量中更好吗?我应该在会话中存储哪种数据?
Because I need information about the user-type in various views, I have been calling Auth::user()
in several places and I am beginning to think that this is adding some load on the DB. Is it better to store the user-type in a session variable and what kind of data should I be storing in my session?
将其存储在会话中不是问题.
It wouldn't be an issue storing it in the session.
在User
类的is_manager
函数中,您可以执行以下操作...
In the is_manager
function in your User
class, you could do something like the following...
public function is_manager()
{
// Check if the session has been set first.
if(\Session::has('is_manager')) {
return \Session::get('is_manager');
}
// Do your necessary logic to determine if the user is a manager, ex...
$is_manager = $this->roles()->where('name', '=', 'manager')->count() == 1;
// Drop it in the session
\Session::put('is_manager', $is_manager);
return $is_manager;
}
请记住,如果您将会话驱动程序设置为数据库,那么这显然无济于事.
Keep in mind if your session driver is set to database, then this obviously isn't going to help.