我应该将哪些数据存储在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:

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:

In Controller:

public function someMethod(){
    $user = Auth::user();
    return view('applications.show', compact('user'));
}

In View:

if($user->is_manager)
   // do this
else if($user->is_admin)
  // do that 

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?

我是laravel的新手。 我一直在使用不同类型用户的laravel 5应用程序。 我需要有关我的视图的不同部分当前登录的用户类型的信息: p>

目前,我已经在各种控制器方法和用户对象上执行类似下面的操作,我可以 确定我在视图中的用户类型: p>

在控制器中: p>

  public function someMethod(){
 $ user =  Auth :: user(); 
返回视图('applications.show',compact('user')); 
} 
  code>  pre> 
 
 

在视图中:

  if($ user-> is_manager)
 //执行此操作
else if($ user-> is_admin)
 //做那个
  code  >  pre> 
 
 

因为我需要有关各种视图中用户类型的信息,所以我在几个地方调用了 Auth :: user() code>,我开始 认为这会在DB上增加一些负载。 将用户类型存储在会话变量中以及我应该在会话中存储哪种数据更好吗? p> div>

It wouldn't be an issue storing it in the session.

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.

We have organized common model calls as follows;

  • Base classes for controllers, models, libraries, composers, commands and jobs which get these models. All related classes extend from these base classes thus have everything they have.
  • Master view composer to serve as base data gatherer for all views.
  • Query caching through Redis. All the above classes get the user through a cached query with timeout of an hour thus the query is executed only once per hour per user.