Laravel: request->user() in boot() method on model (GlobalScope)












1















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?










share|improve this question



























    1















    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?










    share|improve this question

























      1












      1








      1








      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?










      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 10:05









      OdysseeOdyssee

      681419




      681419
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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.






          share|improve this answer


























          • 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











          • 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













          • 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











          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
          });


          }
          });














          draft saved

          draft discarded


















          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









          0














          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.






          share|improve this answer


























          • 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











          • 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













          • 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
















          0














          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.






          share|improve this answer


























          • 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











          • 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













          • 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














          0












          0








          0







          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 3 at 9:21

























          answered Jan 2 at 10:16









          Vaggelis KspsVaggelis Ksps

          190210




          190210













          • 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











          • 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













          • 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



















          • 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











          • 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













          • 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

















          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




















          draft saved

          draft discarded




















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith