简体   繁体   中英

How to set default user for guest users in laravel 5?

Is it possible to create some user which will automatically included if user is not authenticated? For example, if I call $request->user() in controller I will get NULL . I want to get some default user model in this case (maybe instance of App\\User with id == 0). I need it because I want to attach some roles and permissions to guest users via entrust module.

You could add a simple middleware that would authenticate users as Guest user if they aren't authenticated. The code below should do the trick:

class LoginAsGuest {
  public function handle($request, Closure $next)
  {
    if (!Auth::id()) {
      Auth::loginUsingId($guestUserId);
    }
  }
}

Make sure this middleware runs last so that user has a chance to be authenticated using their session/cookie data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM