Reputation: 35
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
Reputation: 17566
findOrFail
and 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
Reputation: 29278
You have your methods in the wrong order.
findOrFail
executes the query immediately, which returns the User
record for $user_id
.
Chaining that to ->with()
will start a new query.
Finally, calling ->first()
returns the first User
from the database.
Adjust your query as such:
User::with('posts')->findOrFail($user_id);
Upvotes: 2