Laravel在Controller构造函数中读取用户ID

时间:2015-04-27 12:35:43

标签: authentication laravel

在我的控制器中,我没有在每个方法中提取Auth::id(),而是在控制器的类中设置了$id属性,并在构造函数。那么,在其他方法中,我只是引用$this->id,它被认为是安全的还是我做错了什么?

代码示例:http://pastebin.com/pvju54eh

2 个答案:

答案 0 :(得分:1)

您可以做的是在控制器中注入Guard实例,然后将当前登录的用户(如果有的话)分配给类属性:

<?php namespace App\Http\Controllers;

use Illuminate\Contracts\Auth\Guard;

class SomeController extends Controller
{
    protected $auth;
    protected $user;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
        $this->user = $this->auth->user();
    }

    public function someMethod()
    {
        // Get logged in user’s ID
        $userId = $this->user->id;
    }
}

答案 1 :(得分:0)

即使我没有看到经常使用的方法,我也没有看到这种方法存在任何重大问题。

我自己觉得从请求中获取控制器中的$ request-&gt; user()更容易。

相关问题