Reputation: 769
In my controller i'm doing
$user = Auth:user()->get();
dd($user);
This is giving me the list of all users from my database. why?
Upvotes: 1
Views: 1575
Reputation: 1347
return User::where('id', auth()->id())->with(['something'])->first()
Upvotes: 0
Reputation: 5083
The other answers either explain how to solve your problem but not properly why this happens.
The laravel documentation states (source):
The
get
method returns anIlluminate\Support\Collection
containing the results where each result is an instance of the PHPStdClass
object.
With the full documentation found here, with API references here.
In essence, the get
function here returns a collection and not the User
object. The get method on an QueryBuilder
executes a select statement.
With the following snippet we can see what queries get executed.
DB::enableQueryLog();
Auth::user()->get();
dump(DB::getQueryLog());
DB::enableQueryLog();
Auth::user()->where('id', 1)->get();
dump(DB::getQueryLog());
The first query will indeed output the expected user, the second query will grab the user class from the Auth::user()
and select all rows from that table.
When we execute the 3rd and 4th query we can see that we once more first get the expected user, the 4th query however does also get a user (in this case the user with id 1). This is due too the where
and not the Auth::user()
.
What we can conclude from these results is that the get takes into account all query builder functions but not the parameters of the supplied class. If you use a get on an object it will only take into account the Class of that Object.
As too solve your problem the other questions where correct and you can use:
$user = Auth::user();
To fetch the user.
Upvotes: 4
Reputation: 1773
You can auth user data by :
$user = Auth::user(); instead of using get();
Your user id is: {{ $user->id }}
Your first name is: {{ $user->first_name }}
Your last name is: {{ $user->last_name }}
Upvotes: 0
Reputation: 2736
Just remove get() to get single user data
$user = Auth:user();
dd($user);
in this case get() method return user collection object
Upvotes: 0