1

After using the Illuminate\Auth\Authenticatable trait on a model, I can now do Auth::id() in places in my app (when the current auth-ed thing is that particular model).

Is there a way to get the class / type of the auth-ed model?

Perhaps something like Auth::model() which might return the model's class name (such as App\Models\User or App\Models\MyCustomAuthCapabaleModel)?

Dan.
  • 609
  • 1
  • 6
  • 17
  • Please share more details. Which trait do you use **exactly**? – Nico Haase Oct 28 '22 at 11:30
  • @NicoHaase `Illuminate\Auth\Authenticatable` - I don't know for a fact that it provides the feature I'm asking for, though. I was just stating that I used it to be able to do Auth::id(). The main question is - is there a way to get the auth-ed model. – Dan. Oct 28 '22 at 11:33
  • That trait does not contain an `id()` method in Laravel 8 or 9. Can you share more details about how you use that trait? – Nico Haase Oct 28 '22 at 11:44
  • Also, does https://stackoverflow.com/questions/64787214/how-to-get-user-id-in-controllers-laravel-8 help? – Nico Haase Oct 28 '22 at 11:45
  • 1
    Are you looking for `Auth::user()` ? – Techno Oct 28 '22 at 11:47
  • @NicoHaase - doing `Auth::id()` calls `getAuthIdentifier()` on that trait. – Dan. Oct 28 '22 at 11:50
  • 1
    @Techno - yes you're right, that does it (well adding `::class` to the end of your snippet anyway). I guess I overlooked it as I was looking for something more generic than the word `user`. Perhaps I've misunderstood that the `Authenticatable` was designed to be used with 'things' that represent 'things' other than only users. – Dan. Oct 28 '22 at 11:52
  • @NicoHaase - re that other linked questions - kind of, but I think I would've still inadvertently overlooked it as per my other comment above. – Dan. Oct 28 '22 at 11:53
  • @Dan. Thanks for letting us know! I've added an answer to the question with a little explaination for you :) – Techno Oct 28 '22 at 12:00

2 Answers2

1

Auth::user(); returns the model of the logged in user.

If you ever wish to change the User model, you can change it in config/auth.php at the key providers.users.model

Techno
  • 1,668
  • 1
  • 9
  • 19
  • 1
    I didn't have to add anything to the config file to make Auth::user() work with other models, but looks like I might need to look into / address the config file thing to make other things work. – Dan. Oct 28 '22 at 12:07
  • I'm sorry if my wording is unclear. I meant to say that it returns the model listed in your config. If at any point in time you wish to change the `User` model, you can change it here. `Auth::user()` should then return the new class :) – Techno Oct 28 '22 at 12:09
  • You may also use `auth()->user()` – zoltalar Oct 28 '22 at 13:13
0

Auth::user(); returns all the information about the authenticated user

  • 1
    Thanks for your answer, but I'm going to have to give the points the person who helped out in the comments! – Dan. Oct 28 '22 at 12:05