I would like to use Gates in Laravel 8, but we’re using custom authentication, so Laravel doesn’t know what $user record to pass into the Gate. So how can I tell Laravel that a certain user is currently logged in, so the correct user record will be used?
Thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could use the forUser
method:
Gate::forUser($user)->allows('update-post', $post); // ^^^^^^^^^^^^^^
Check this section of the documentation.
Method 2
I do not know if your validation process is done in the AppServiceProvider file or in the controller.
But I think after the validation in the controller, you can use the function
Auth::setUser($user)
Method 3
So this is what I did:
In AppModels
, I made a User class that extends IlluminateFoundationAuthUser
I also set protected properties in that class of $table
and $primaryKey
to specify my custom table name and primary key name.
Then in my middleware, where I check to see if the user is logged in, if he or she is, then I run this:
IlluminateSupportFacadesAuth::login(AppModelsUser::find($userId))
When I do all this, I can use Auth::user()
wherever I want. Presumably, gates will now work without specifying the user every time.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0