https://laravel.com/docs/8.x/eloquent-relationships#updating-belongs-to-relationships
Based on the documentation, you should call the save method after the associate
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a one to many relationship between users and roles. I am unable to associate a role to a user while saving or updating a user. Please spare some time to have a look below. Thank you for your time.
Users
----------
* id
* name
* email
* password
* role_id
* created_at
Roles
----------
* id
* name
* slug
* created_at
public function role() {
return $this->belongsTo(Role::class);
}
public function users() {
return $this->hasMany(User::class);
}
public $showUserUpdationModal = false;
public $role;
public User $user;
protected $rules = [
'user.name' => 'required|string|max:255',
'user.email' => 'required|string|email|max:255',
'role' => 'required',
];
public function storeUser()
{
$this->validate();
$this->validate([
'user.email' => 'unique:users,email,'.$this->user->id,
]);
$this->user->save();
$this->user->role()->associate($this->role);
$this->showUserUpdationModal = false;
$this->dispatchBrowserEvent('notify', $this->user->name.' Updated Successfully');
$this->emit('sectionRefresh');
}
https://laravel.com/docs/8.x/eloquent-relationships#updating-belongs-to-relationships
Based on the documentation, you should call the save method after the associate
Please or to participate in this conversation.