Get posts belongs to a specific user in Laravel

You can get posts belongs to a specific user in Laravel. Sometimes we have to get all records from posts table which are created by a specific or logged in user. In that case it will help you to find the records from posts table.

Answers 1
  • Get all posts created by logged in user with whereBelongsTo method in Laravel 8

    $user = App\Models\User::find(Auth::user()->id);
    $posts = App\Models\Post::whereBelongsTo($user)->get();
    dd($posts);
    
    //Or - You can specify the relationship name manually by providing it as the second argument. You can create method with name of user using belongsTo() relation in post model.
    $user = App\Models\User::find(1);
    $posts = App\Models\Post::whereBelongsTo($user, 'user')->get();
    dd($posts);
    
    //Code for demo:
    Route::get('/get-posts-by-user', function(){
        $user = App\Models\User::find(1);
        $posts = App\Models\Post::whereBelongsTo($user)->get();
        dd($posts);
    });
    
    0

    Output:

    Illuminate\Database\Eloquent\Collection {#1631 ▼
      #items: array:17 []
    }

     

    This code snippet will help you to get all the records from the posts table which are created by a specific user in Laravel.

    You have to create a foreing key (user_id) in posts table which is the primary key of the users table in database.

    You have to also specify the belongsTo() relationship in post model with name user or you can use different name like author as per your requirment.

    user relationship using belongsTo() method in Post model

    public function user(){
        return $this->belongsTo('App\Models\User');
    }
  • Back to code snippet queries related laravel