Laravel: request->user() in boot() method on model (GlobalScope)
I have some behaviour I cannot explain. I am in the middle of a rather big refactor and I bumped into an issue that has been in the code for a long time, but it seemed to work before the refactor.
On some models static::addGlobalScope
is used to extend some queries where needed. In this callback method the user that performs the request is fetched with request()->user()
. This works inside the callback without issues, but when moved outside the callback this returns null
.
Working example:
protected static function boot()
{
parent::boot();
static::addGlobalScope('auth', function (Builder $builder) {
$user = request()->user();
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
Example where $user
is null.
protected static function boot()
{
parent::boot();
$user = request()->user(); // Moved $user outside of the callback
static::addGlobalScope('auth', function (Builder $builder) use ($user) {
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
The second example has been taken from a model before the refactor.
This method is being used on multiple models, this never gave any issues. Does anyone have an idea why $user
is null when request()->user()
is called outside of the callback in the boot
method? And most important, why it never gave issues before?
php laravel eloquent
add a comment |
I have some behaviour I cannot explain. I am in the middle of a rather big refactor and I bumped into an issue that has been in the code for a long time, but it seemed to work before the refactor.
On some models static::addGlobalScope
is used to extend some queries where needed. In this callback method the user that performs the request is fetched with request()->user()
. This works inside the callback without issues, but when moved outside the callback this returns null
.
Working example:
protected static function boot()
{
parent::boot();
static::addGlobalScope('auth', function (Builder $builder) {
$user = request()->user();
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
Example where $user
is null.
protected static function boot()
{
parent::boot();
$user = request()->user(); // Moved $user outside of the callback
static::addGlobalScope('auth', function (Builder $builder) use ($user) {
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
The second example has been taken from a model before the refactor.
This method is being used on multiple models, this never gave any issues. Does anyone have an idea why $user
is null when request()->user()
is called outside of the callback in the boot
method? And most important, why it never gave issues before?
php laravel eloquent
add a comment |
I have some behaviour I cannot explain. I am in the middle of a rather big refactor and I bumped into an issue that has been in the code for a long time, but it seemed to work before the refactor.
On some models static::addGlobalScope
is used to extend some queries where needed. In this callback method the user that performs the request is fetched with request()->user()
. This works inside the callback without issues, but when moved outside the callback this returns null
.
Working example:
protected static function boot()
{
parent::boot();
static::addGlobalScope('auth', function (Builder $builder) {
$user = request()->user();
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
Example where $user
is null.
protected static function boot()
{
parent::boot();
$user = request()->user(); // Moved $user outside of the callback
static::addGlobalScope('auth', function (Builder $builder) use ($user) {
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
The second example has been taken from a model before the refactor.
This method is being used on multiple models, this never gave any issues. Does anyone have an idea why $user
is null when request()->user()
is called outside of the callback in the boot
method? And most important, why it never gave issues before?
php laravel eloquent
I have some behaviour I cannot explain. I am in the middle of a rather big refactor and I bumped into an issue that has been in the code for a long time, but it seemed to work before the refactor.
On some models static::addGlobalScope
is used to extend some queries where needed. In this callback method the user that performs the request is fetched with request()->user()
. This works inside the callback without issues, but when moved outside the callback this returns null
.
Working example:
protected static function boot()
{
parent::boot();
static::addGlobalScope('auth', function (Builder $builder) {
$user = request()->user();
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
Example where $user
is null.
protected static function boot()
{
parent::boot();
$user = request()->user(); // Moved $user outside of the callback
static::addGlobalScope('auth', function (Builder $builder) use ($user) {
if ($user) {
if ($user->role == 'consultant') {
$builder->where('user_id', $user->id);
} elseif ($user->role == 'approver') {
$builder->whereHas('contract', function ($query) use ($user) {
return $query->whereHas('approvers', function ($query) use ($user) {
return $query->where('user_id', $user->id);
});
});
}
}
});
}
The second example has been taken from a model before the refactor.
This method is being used on multiple models, this never gave any issues. Does anyone have an idea why $user
is null when request()->user()
is called outside of the callback in the boot
method? And most important, why it never gave issues before?
php laravel eloquent
php laravel eloquent
asked Jan 2 at 10:05
OdysseeOdyssee
681419
681419
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
This may have to do with the fact that in order to get the user when you use request()->user() it has to register all the global scopes and then execute the query. It actually checks if session exists and then queries to get that user to return user object. Maybe you need to use local scope or maybe Auth::check() will do the job.
When I placerequest->user()
outside the callback, this returnsnull
. When placed inside the callback, it works as expected. I do however seem to remember that I once read that therequest()
method does not work insideboot()
methods in laravel, but why and how I do not know.
– Odyssee
Jan 2 at 10:29
Did you changed the laravel version? Maybe now boot hooks of the models run before session middleware. Can you try this? Auth::user();
– Vaggelis Ksps
Jan 2 at 10:32
Laravel has been updated indeed,Auth::user()
does not work outside the callback. When placed inside the callbackAuth::user()
works as intended.
– Odyssee
Jan 2 at 11:14
Can you add a dd($user) before static::addGlobalScope and post what you get?
– Vaggelis Ksps
Jan 2 at 13:05
As stated in the question, this returnsnull
. This issue has something to do with the session midleware. I'm getting close with finding the issue. Will provide an answer when I am certain.
– Odyssee
Jan 3 at 6:40
|
show 1 more comment
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54004381%2flaravel-request-user-in-boot-method-on-model-globalscope%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This may have to do with the fact that in order to get the user when you use request()->user() it has to register all the global scopes and then execute the query. It actually checks if session exists and then queries to get that user to return user object. Maybe you need to use local scope or maybe Auth::check() will do the job.
When I placerequest->user()
outside the callback, this returnsnull
. When placed inside the callback, it works as expected. I do however seem to remember that I once read that therequest()
method does not work insideboot()
methods in laravel, but why and how I do not know.
– Odyssee
Jan 2 at 10:29
Did you changed the laravel version? Maybe now boot hooks of the models run before session middleware. Can you try this? Auth::user();
– Vaggelis Ksps
Jan 2 at 10:32
Laravel has been updated indeed,Auth::user()
does not work outside the callback. When placed inside the callbackAuth::user()
works as intended.
– Odyssee
Jan 2 at 11:14
Can you add a dd($user) before static::addGlobalScope and post what you get?
– Vaggelis Ksps
Jan 2 at 13:05
As stated in the question, this returnsnull
. This issue has something to do with the session midleware. I'm getting close with finding the issue. Will provide an answer when I am certain.
– Odyssee
Jan 3 at 6:40
|
show 1 more comment
This may have to do with the fact that in order to get the user when you use request()->user() it has to register all the global scopes and then execute the query. It actually checks if session exists and then queries to get that user to return user object. Maybe you need to use local scope or maybe Auth::check() will do the job.
When I placerequest->user()
outside the callback, this returnsnull
. When placed inside the callback, it works as expected. I do however seem to remember that I once read that therequest()
method does not work insideboot()
methods in laravel, but why and how I do not know.
– Odyssee
Jan 2 at 10:29
Did you changed the laravel version? Maybe now boot hooks of the models run before session middleware. Can you try this? Auth::user();
– Vaggelis Ksps
Jan 2 at 10:32
Laravel has been updated indeed,Auth::user()
does not work outside the callback. When placed inside the callbackAuth::user()
works as intended.
– Odyssee
Jan 2 at 11:14
Can you add a dd($user) before static::addGlobalScope and post what you get?
– Vaggelis Ksps
Jan 2 at 13:05
As stated in the question, this returnsnull
. This issue has something to do with the session midleware. I'm getting close with finding the issue. Will provide an answer when I am certain.
– Odyssee
Jan 3 at 6:40
|
show 1 more comment
This may have to do with the fact that in order to get the user when you use request()->user() it has to register all the global scopes and then execute the query. It actually checks if session exists and then queries to get that user to return user object. Maybe you need to use local scope or maybe Auth::check() will do the job.
This may have to do with the fact that in order to get the user when you use request()->user() it has to register all the global scopes and then execute the query. It actually checks if session exists and then queries to get that user to return user object. Maybe you need to use local scope or maybe Auth::check() will do the job.
edited Jan 3 at 9:21
answered Jan 2 at 10:16
Vaggelis KspsVaggelis Ksps
190210
190210
When I placerequest->user()
outside the callback, this returnsnull
. When placed inside the callback, it works as expected. I do however seem to remember that I once read that therequest()
method does not work insideboot()
methods in laravel, but why and how I do not know.
– Odyssee
Jan 2 at 10:29
Did you changed the laravel version? Maybe now boot hooks of the models run before session middleware. Can you try this? Auth::user();
– Vaggelis Ksps
Jan 2 at 10:32
Laravel has been updated indeed,Auth::user()
does not work outside the callback. When placed inside the callbackAuth::user()
works as intended.
– Odyssee
Jan 2 at 11:14
Can you add a dd($user) before static::addGlobalScope and post what you get?
– Vaggelis Ksps
Jan 2 at 13:05
As stated in the question, this returnsnull
. This issue has something to do with the session midleware. I'm getting close with finding the issue. Will provide an answer when I am certain.
– Odyssee
Jan 3 at 6:40
|
show 1 more comment
When I placerequest->user()
outside the callback, this returnsnull
. When placed inside the callback, it works as expected. I do however seem to remember that I once read that therequest()
method does not work insideboot()
methods in laravel, but why and how I do not know.
– Odyssee
Jan 2 at 10:29
Did you changed the laravel version? Maybe now boot hooks of the models run before session middleware. Can you try this? Auth::user();
– Vaggelis Ksps
Jan 2 at 10:32
Laravel has been updated indeed,Auth::user()
does not work outside the callback. When placed inside the callbackAuth::user()
works as intended.
– Odyssee
Jan 2 at 11:14
Can you add a dd($user) before static::addGlobalScope and post what you get?
– Vaggelis Ksps
Jan 2 at 13:05
As stated in the question, this returnsnull
. This issue has something to do with the session midleware. I'm getting close with finding the issue. Will provide an answer when I am certain.
– Odyssee
Jan 3 at 6:40
When I place
request->user()
outside the callback, this returns null
. When placed inside the callback, it works as expected. I do however seem to remember that I once read that the request()
method does not work inside boot()
methods in laravel, but why and how I do not know.– Odyssee
Jan 2 at 10:29
When I place
request->user()
outside the callback, this returns null
. When placed inside the callback, it works as expected. I do however seem to remember that I once read that the request()
method does not work inside boot()
methods in laravel, but why and how I do not know.– Odyssee
Jan 2 at 10:29
Did you changed the laravel version? Maybe now boot hooks of the models run before session middleware. Can you try this? Auth::user();
– Vaggelis Ksps
Jan 2 at 10:32
Did you changed the laravel version? Maybe now boot hooks of the models run before session middleware. Can you try this? Auth::user();
– Vaggelis Ksps
Jan 2 at 10:32
Laravel has been updated indeed,
Auth::user()
does not work outside the callback. When placed inside the callback Auth::user()
works as intended.– Odyssee
Jan 2 at 11:14
Laravel has been updated indeed,
Auth::user()
does not work outside the callback. When placed inside the callback Auth::user()
works as intended.– Odyssee
Jan 2 at 11:14
Can you add a dd($user) before static::addGlobalScope and post what you get?
– Vaggelis Ksps
Jan 2 at 13:05
Can you add a dd($user) before static::addGlobalScope and post what you get?
– Vaggelis Ksps
Jan 2 at 13:05
As stated in the question, this returns
null
. This issue has something to do with the session midleware. I'm getting close with finding the issue. Will provide an answer when I am certain.– Odyssee
Jan 3 at 6:40
As stated in the question, this returns
null
. This issue has something to do with the session midleware. I'm getting close with finding the issue. Will provide an answer when I am certain.– Odyssee
Jan 3 at 6:40
|
show 1 more comment
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54004381%2flaravel-request-user-in-boot-method-on-model-globalscope%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown