alcolopa
alcolopa

Reputation: 35

Get a user with posts

I am trying to get a user with his posts in laravel, so far I have tried to use the following line

User::findOrFail($user_id)->with('posts')->first();

But I am getting the first user on the table regardless of what the user ID specified is.

I have tried to dd the user_id and it's working fine, (getting the user_id from the route).

So far the result I am getting is if the user id is x and the first user in the table has an id of 1 I get the info of user id 1 and his posts.

Thanks in advance!

Upvotes: 2

Views: 661

Answers (2)

Maik Lowrey
Maik Lowrey

Reputation: 17566

findOrFailand first will give you the User Object but you have to decide witch function you will use.

If you use Routemodel Binding then you can use: User::with('posts')->first(); or User::load('posts');

If you dont use routemodel Binding you can use findOrFail like that: User::with('posts')->findOrFail($user_id);

Upvotes: 0

Tim Lewis
Tim Lewis

Reputation: 29278

You have your methods in the wrong order.

  1. findOrFail executes the query immediately, which returns the User record for $user_id.

  2. Chaining that to ->with() will start a new query.

  3. Finally, calling ->first() returns the first User from the database.

Adjust your query as such:

User::with('posts')->findOrFail($user_id);

Upvotes: 2

Related Questions