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.
findOrFailexecutes the query immediately, which returns theUserrecord for$user_id.Chaining that to
->with()will start a new query.Finally, calling
->first()returns the firstUserfrom 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);
