skip to Main Content

I am currently working on a Laravel project and encountering an issue with Eloquent relationships. I have two models, User and Post, and I’m trying to establish a one-to-many relationship between them. However, I’m facing issues when trying to retrieve the related posts for a user

User Model

class Post extends Model {
    // ...
    public function user() {
        return $this->belongsTo(User::class);
    }
}

Post Model

class Post extends Model {
    // ...
    public function user() {
        return $this->belongsTo(User::class);
    }
}

Now, when I try to retrieve the posts for a user using the following below code

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

I’m not getting the expected results and $posts is empty I have ensured that there are posts with the user in the database

2

Answers


  1. Thing you need to do is create a hasMany relationship in the User model,
    then create a belongsTo relationship in the Post model.

    User Model

    class User extends Model{
        // ...
        public function post(){
            return $this->hasMany(Post::class, 'foreign_key', 'local_key');
        }
    }
    

    Post Model

    class Post extends Model{
        // ...
        public function user(){
            return $this->belongsTo(User::class, 'foreign_key', 'owner_key');
        }
    }
    

    For more details, you can see it in the Laravel documentation https://laravel.com/docs/10.x/eloquent-relationships#one-to-many

    Login or Signup to reply.
  2. You need to change you User model with this

    class User extends Model{
        public function posts(){
            return $this->hasMany(Post::class);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search