How to query user with posts in Laravel

前端 未结 2 1210
走了就别回头了
走了就别回头了 2021-01-03 08:22

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

相关标签:
2条回答
  • 2021-01-03 08:44

    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

    0 讨论(0)
  • 2021-01-03 08:47

    You can simply use also this.

    public function($id){
    $posts = Posts::where('uid','=',auth()->user()->id)->findOrFail($id);
    return view('your_blade.php',compact('posts'));
    
    OR either you can return this
    
    return response()->json([$posts], 200);
    
    
    }
    

    Note: don't forgot to add trait also use App\Posts;

    0 讨论(0)
提交回复
热议问题