Shortcut/Shorten To Get Authenticated User ID in Laravel 8

In this post, I will share a simple example of how to get the user ID of the authenticated user in Laravel 8. Using the auth() helper function or Auth class in Laravel 8 you will easily get the user ID.

Created on: Sep 02, 2021
2,141
Shortcut/Shorten To Get Authenticated User ID in Laravel 8

In this post, I will share a simple example of how to get the user ID of the authenticated user in Laravel 8. Using the auth() helper function or Auth class in Laravel 8 you will easily get the user ID.

The question is how?

First, we know that auth()->user() or \Auth::user() we can access the authenticated user details from the users table.

So getting the user ID you can access it with the sample below:

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

//or

echo \Auth::user()->id;

But we can shorten it by removing the user() function. Now it will become like this:

echo auth()->id();

//or

echo \Auth::id();

Now the result of the code above is the same but the difference is your code is shorter.

That's pretty much it. I hope it helps.

Cheers :)

Leave a Comment