2015-02-08 47 views
1

我有一个会话表,我通过在REST API中进行身份验证来为用户创建会话。在雄辩的模型范围内检索请求实例

会话与用户有关系,所以我可以从会话中检索用户对象。

我想创建一个Eloquent作用域来检索登录的当前用户,如Session::currentUser()->id其中授权标头等于会话表中的标记。

看来我不能在我的scopeCurrentUser()中使用Request实例。通过控制器不能把它注射以及这样的:

public function __construct(Request $request) { 
    $this->request = $request; 
} 

还试图把它注入方法(这是可能的,因为Laravel 5)

public function scopeCurrentUser($query, Request $request) 
{ 
    return $query->where('token', $request->header('Authorization')); 
} 

什么办法可以得到$request->header('Authorization')

+0

告诉我们你试过的东西。 – Marwelln 2015-02-08 15:54:56

+0

@Marwelln完成! – guidsen 2015-02-08 15:58:58

回答

1

您可以使用app('Illuminate\Http\Request')Request::(请确保您的文件顶部有use Request;)获取请求实例。

因此,无论你有

use Request; 

public function scopeCurrentUser($query) 
{ 
    return $query->where('token', Request::header('Authorization')); 
} 

public function scopeCurrentUser($query) 
{ 
    return $query->where('token', app('Illuminate\Http\Request')->header('Authorization')); 
} 

你不能做雄辩方法依赖注入,据我所知(至少它没有当我试图努力)。

+0

大声笑....导入错误的命名空间.. – guidsen 2015-02-08 16:29:38