Home > Enterprise >  Get a user with posts
Get a user with posts

Time:03-15

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!

CodePudding user response:

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);

CodePudding user response:

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);

  • Related