doumen1883 2015-12-08 20:18
浏览 87
已采纳

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

  • 写回答

2条回答 默认 最新

  • doufei5315 2015-12-08 20:45
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点