简体   繁体   中英

Laravel Auth user id in controller

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?

You need to use the Auth facade in the controller;

add this line just before class definition.

use Auth;

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

Add the following line before the Class definition

use Auth;

Get your current user id using the following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM