I have User model which has relationships hasMany with UserPosition eloquent model:
User model
public function positions()
{
return $this->hasMany(UserPosition::class);
}
How I can use updateOrCreate method when from request come array of data positions?
Code
$positions = [
"doctor",
"developer"
];
$user->positions()->each(function($position) use ($positions, $user) {
$id = $user->id;
foreach ($positions as $name) {
$position->updateOrCreate(['user_id' => $id, 'name' => $name], [
'name' => $name
]);
}
});
Note: In this example user doesn't has any positions on the table of database
But my code not work. Why?