Reputation: 2403
I have a Session table where I create sessions for users by authenticating in a REST API.
A Session has a relation with a User, so I can retrieve the User object from the Session.
I want to create a Eloquent scope to retrieve the currentUser logged in like Session::currentUser()->id
where the Authorization header equals the token in the Session table.
It seems I can't use the Request instance in my scopeCurrentUser()
. Can't inject it via the Controller as well like this:
public function __construct(Request $request) {
$this->request = $request;
}
Also tried to inject it into the method (which is possible since Laravel 5)
public function scopeCurrentUser($query, Request $request)
{
return $query->where('token', $request->header('Authorization'));
}
Any way I can get the $request->header('Authorization')
?
Upvotes: 3
Views: 3672
Reputation: 29423
You can get the request instance by using app('Illuminate\Http\Request')
or Request::
(make sure you have use Request;
at the top of you file).
So either you have
use Request;
public function scopeCurrentUser($query)
{
return $query->where('token', Request::header('Authorization'));
}
or
public function scopeCurrentUser($query)
{
return $query->where('token', app('Illuminate\Http\Request')->header('Authorization'));
}
You can't do dependency injection in Eloquent methods as far as I know (at least it didn't work when I tried it).
Upvotes: 2