0

I use the baked in Auth in Laravel 5.0, which is such a head-start. What I can't figure out is how to query the database with an authenticated User's ID.

E.g. "Get all the posts for User ID 1".

From the User.php model, I can see the following function:

getId();

but,

$userid = getId(); 

doesn't work.

How would I define or grab the userID so that I can query my database on user-based variables?

1 Answer 1

5

From a controller, you can use Auth::user() to get the logged in user, and Auth::user()->id to get the logged in user's id.

Also note that you can use Auth::id() as a shortcut for Auth::user()->id

Additionally, there are two other methods you could use (from the $request instance and via a function type-hint). You can read about them in the laravel docs.

For your particular question, you could define the $userid as follows: $userid = \Auth::id();

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I get this error: "Class 'Namespace\Http\Controllers\Auth' not found". Should I include use\namespace\user; in my controller?
If you manually generated the controller you need to import the proper namespace with use Illuminate\Routing\Controller;. However, you should really look into generating the controllers with artisan (php artisan make:controller PhotoController). You can read more about it here.
@matt You have to reference it using a backslash \Auth::user() or add an import statement user Auth; at the top. Also note that you can use Auth::id() as a shortcut for Auth::user()->id
@lukasgeiter thank you so much! Great contribution. I didn't realize about the backslash - is that because it's built into Laravel 5.0?
Take a look at this answer it's about the View class but the principle is the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.