1

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?

1
  • just remove ->get(); Commented May 6, 2017 at 9:23

5 Answers 5

4

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 an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass 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());

This will output: Only get output

DB::enableQueryLog();
Auth::user()->where('id', 1)->get();
dump(DB::getQueryLog());

This will output: Get with where output

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.

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

Comments

0

Because get return collection

Laravel Doc

Comments

0

Just remove get() to get single user data

$user = Auth:user();
dd($user);

in this case get() method return user collection object

Comments

0

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 }}

1 Comment

Although your question does solve the answer it does not give any explanation as too why this is the case (which was specifically asked for in the question)
0

return User::where('id', auth()->id())->with(['something'])->first()

Comments

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.