Reputation: 267
I have a one to many relationship between users
and roles
. I have three roles administrator
, employee
and client
. I am unable to associate the user with a role.
Example:
When I am updating a user with a role administrator
, I am successful in editing and saving the role to employee
and client
, but when I click save when the default role value remains unchanged i.e. administrator
, it throws me an SQLSTATE[22007] error.
Please spare some time to have a look below.
Illuminate\Database\QueryException SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '[3]' for column
management
.users
.role_id
at row 1 (SQL: updateusers
setrole_id
= [3],users
.updated_at
= 2021-01-29 05:08:12 whereid
= 3) http://127.0.0.1:8000/backend/management/audience-management/user
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 updateUser(User $user)
{
$this->resetValidation();
$this->user = $user;
$this->role = $user->role()->pluck('id');
$this->showUserUpdationModal = true;
}
public function storeUser()
{
$this->validate();
$this->validate([
'user.email' => 'unique:users,email,'.$this->user->id,
]);
$this->user->role()->associate($this->role);
$this->user->save();
$this->showUserUpdationModal = false;
$this->dispatchBrowserEvent('notify', $this->user->name.' Updated Successfully');
$this->emit('sectionRefresh');
}
Upvotes: 0
Views: 101
Reputation: 2540
The problem is you are trying to assign the role_id value to an array instead of an integer.
Try saving the role_id as integer role id like:
$user->role_id = 1;
$user->save();
Instead of
$user->role_id = [1];
$user->save();
EDIT
Based on the code,
public function updateUser(User $user)
{
$this->resetValidation();
$this->user = $user;
$this->role = $user->role_id; //This should world now
$this->showUserUpdationModal = true;
}
Upvotes: 1