phplaravellaravel-authenticationlaravel-authorizationlaravel-gate

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


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.


Solution

  • 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.