Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

OrelBitton's avatar

How should I apply this Eloquent relationship?

I have 3 tables:

Users
_____
id
name
password
_____
Categories
_____
id
name
_____
Posts
_____
id
name
user_id
category_id
_____

Post may only have one category and one user. In my models I am using belongsTo on the corresponding models.

0 likes
3 replies
Nathan's avatar

On your Post model:

public function user() 
{
    return $this->belongsTo('App\User');
}

public function category()
{
    return $this->belongsTo('App\Category');
}

Then in both your User and Category model you would have this function:

public function posts()
{
    return $this->hasMany('App\Post');
}

You have a one-to-many relationship between Users and Posts, as well as Categories and Posts. In the future if you want a post to be able to have multiple users or categories associated with it then you would use a many-to-many relationship.

http://laravel.com/docs/5.0/eloquent

OrelBitton's avatar

Hey! thanks for the response. Actually thats what I did but I have not idea how to save a post this way (attaching category and user to a post)

Please or to participate in this conversation.