0

Based on below question answers I am able to retrieve data of particular table but not all three table data in single array . How to retrieve all data using relation?

I tried following ways

  1. This will retrieve all users data instead of particular user

    User::find(1)->with('posts')->get();
    
  2. This will retrieve only post detail not user table

    $data = User::findOrFail(1)->posts()->get();
    

Please help me to retrieve all data of three tables in single user in single query.

1 Answer 1

1

Will get the user with id one with all posts.

$data = User::findOrFail(1)->load('posts');

or

$data = User::with('posts')->findOrFail(1);
echo "Username:" . $data->name;
foreach($data->posts as $post) {
    echo $post->title;
    echo "Comments:";
    foreach($post->comments as $comment) {
        echo $comment->value;
    }
}
11
  • thank you for the answer .how to echo each data .i can able to print data using print_r().
    – scott
    Jul 30, 2015 at 11:10
  • i need to display username including user posts title ?
    – scott
    Jul 30, 2015 at 11:11
  • you can pass them to a view and then loop through the posts.
    – cre8
    Jul 30, 2015 at 11:12
  • ya i tried loop like foreach($data as $dats){ echo $dats->username.'<br>'; echo $dats->post_desc.'<br>'; } but it print only username but post_desc not displaying
    – scott
    Jul 30, 2015 at 11:13
  • the posts as saved in $data->posts
    – cre8
    Jul 30, 2015 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.