Get posts belongs to a specific user in Laravel

Created at 03-Nov-2021 , By samar

Get posts belongs to a specific user in Laravel

Hello everyone, in this post we will look at how to solve "Get posts belongs to a specific user in Laravel" in programming.

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.
  • 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);
    });
    

    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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.