belongsToMany with updateOrCreate

Posted 1 year ago by eddieace

Hi I have this function. It runs every once in a while and I just added every location that a postition have. In a pivot table. The problem now is that every time it runs it adds a new record in the database. So the position gets new locations every time it runs.

Here is the function:

$position = Position::updateOrCreate(['title' => $position->title, company_id => $company_id], $position);

foreach($position->locations() as $location) {

    $location = Location::firstOrCreate(['name' => $location->name]);
    
    $position->locations()->attach($location->id);
}

Is there some way I could

if (if position_location not already exists) {
    $position->locations()->attach($location->id);
}

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.