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

kingashok29's avatar

How do I use associate in Laravel.

Hello, I am building a blog and I want to save comments and replies on a post by using Eloquent. I used proper relationships on all models. But now it is giving me error that user_id does not has a default value. So how do i add a comment on post by just passing comment-body parameter from request and filling post-id and user-id from eloquent automatically.

0 likes
2 replies
Lars-Janssen's avatar

Something like:

$post->save($comment);

Make everything fillable in your models:

for example:


protected $fillable = [
        'user_id'
    ];
gorakhyadav's avatar

You can use like this for Example

class User { public function customer() { return $this->hasOne('Customer'); } }

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

$user = new User($data); $customer = new Customer($customerData);

$customer->user()->associate($user); $customer->save()

Please or to participate in this conversation.