Laravel Auth user id in controller

2020-06-09 06:04发布

问题:

I am using the Laravel boilerplate. I'm trying to get the user_id of the signed in user. I am getting the following error:

Class 'App\Http\Controllers\Frontend\Auth' not found

Here is the call

$user = Auth::user();

Then I try to get the id using:

$user->id

What am I missing?

回答1:

You need to use the Auth facade in the controller;

add this line just before class definition.

use Auth;


回答2:

Try this,

auth()->user()->id;

When you try to get the user by using $user = Auth::user(); Laravel tries to load Auth class from the current location. In your case, it is

'App\Http\Controllers\Frontend'

So Laravel is looking for Auth class inside the Frontend directory, which is not in. That's why you got that error message saying not found as below,

'Class 'App\Http\Controllers\Frontend\Auth' not found'

If you use use Auth; method, you have to type use Auth; in each and every controller that you are going to use the Auth controller.

Instead of typing use Auth; in each and every controller you can simply use the Laravel helper function as auth()->user().

from that you can get any value from the db like:

auth()->user()->id

auth()->user()->f_name


回答3:

Add the following line before the Class definition

use Auth;

Get your current user id using the following code:

$currentuserid = Auth::user()->id;