0

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?

2 Answers 2

2

You are iterating on the existing positions of a user, meaning that if a user has no positions the iteration will never happen. You can iterate along the positions you need to make:

$positions = collect([
    "doctor",
    "developer"
]);

$positions->each(function($position) use ($user) {
        $user->positions()->updateOrCreate(['name' => $position], [
            'name' => $position
        ]);
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

You're do this without looping? I think what $name here is undefined am I right? I must replace var $name wiht $position in your case? @apokryfos
Yes you're right. There is still looping being done but it's over the $positions collection
I don't see why this is the excepted answer, updateOrCreate() won't work on a collection of models and $user->positions() is returning a collection, in order for this to work you must use firstOrCreate() directly on the Position model class, like I defined in the answer below.
0

It doesn't work because your running your updateOrCreate() method inside an each iteration which never runs because as you stated in your note "this example user doesn't has any positions on the table of database"

Here your trying to loop through your currently existing positions attached to your user model:

$user->positions()->each()

But that won't run because the user doesn't have any positions at the moment.

I'm guessing you are trying to update the the user's positions, where it is possible that the user already has one or more of those positions associated to him and you don't want to create duplicates, for that you can do this:

$positions = [
    "doctor",
    "developer"
];

foreach($positions as $position) {
    UserPosition::firstOrCreate(['user_id' => $user->id, 'name' => $position]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.