In Laravel, how can you use a Gate if you're using custom authentication?

1.9k views Asked by At

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.

3

There are 3 answers

0
Magmatic On BEST ANSWER

So this is what I did:

In \App\Models, I made a User class that extends Illuminate\Foundation\Auth\User

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:

\Illuminate\Support\Facades\Auth::login(\App\Models\User::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.

2
Kenny Horna On

You could use the forUser method:

Gate::forUser($user)->allows('update-post', $post);
//    ^^^^^^^^^^^^^^

Check this section of the documentation.

0
Mohammad Akbari On

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)