Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 810
Joe Avatar asked Jul 22 '15 23:07

Joe


People also ask

How can I get Laravel 8 Controller ID?

$id = Auth::id(); // Retrieve the currently authenticated user's ID... $user = $request->user(); // returns an instance of the authenticated user... $id = $request->user()->id; // Retrieve the currently authenticated user's ID... $user = auth()->user(); // Retrieve the currently authenticated user...

How can I get my Laravel username?

$user_id = DB::table('users')->where('username', $user_input)->first()->id; html. laravel. css.

How can I get Laravel API ID?

You can use auth()->user()->id or Auth::user()->id to get current user id.


2 Answers

You need to use the Auth facade in the controller;

add this line just before class definition.

use Auth;
like image 126
Ammadu Avatar answered Oct 02 '22 23:10

Ammadu


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
like image 27
Kavinda Prabhath Avatar answered Oct 03 '22 00:10

Kavinda Prabhath