How to query user with posts in Laravel

laravel, php

Solution

Right now, it is possible to get the `Posts` by first getting the `User` then using that ID, getting the `Posts`. Note: this is not the recommended way of using Laravel with relationships:

$user = User::find($id);
$posts = Post::where("user_id", "=", $user->id)->get();

While this would work (assuming you had a model for `Post` with a `user_id` key), but the correct way is to define the relationship in the models. For this one, it would be `hasMany()` and `belongsTo()` on `User` and `Post` respectfully. Here is your `User.php` model class:

class User extends Eloquent {
  protected $table = "users";

  public function posts(){
    return $this->hasMany("Post");
  }
}

And make sure to define the inverse in your `Post.php` model class:

class Post extends Eloquent {
  protected $table = "posts";

  public function user(){
    return $this->belongsTo("User");
  }
}

Lastly, you can query this relationship in your controller using the following:

$user = User::find($id);
$posts = $user->posts()->get();

This will also enforce integrity by forcing any updates/saves to use the right `user_id` key. There's some pretty extensive documentation on how to use the `Eloquent` style of database querying, check it out here:

Laravel - Eloquent

Hope that helps!

Edit

To pass this to a view, add the following to your controller:

public function view_post($id){
    $user = User::find($id);
    $posts = $user->posts()->get();

    return View::make("view")->with(array("user" => $user, "posts" => $posts));
}

You will need a file in your `app/views` directory named (in this case) `view.blade.php` which "echos" all the information about the user and the posts:

<h2>User: {{ $user->id }} - {{ $user->email }}</h2>
<br/>
<h2>Posts:</h2>
@foreach($posts AS $post)
<p> {{ $post->id }}: {{ $post->content }}</p>
@endforeach

Etc etc. Note, I have no idea what columns your `users` and `posts` table has, but using `$user->column` or `$post->column` will echo the contents of that named column.

Here's the documentation for `Views and Responses`, which would help you with this issue:

Laravel - Views and Responses

Problem

I'm new to Laravel. I want to display all post including the user who posted the post. I have a simple query which displays all post, and displays selected post using post id. ``` public function view_post($id) { $post = User::find($id); dd($post); } ``` This is working perfectly fine but I wanted to display all post with the user who posted the post. How can I do this in proper way?

Original source