BelongsToMany with pivot update Or create using Sync - Laravel

We can use attach or detach but it just doesn't feel right, the one i need is sync, below is the structure i needed to make it work.

Table : games

id
name
slug

Table : platforms
id
name
slug

Table : game_platform
game_id
platform_id
released_at
requirement_minimum
requirement_recommended

Make sure to set relationship to belongsToMany with the second args 'game_platform' and withPivot all the fields needed, if you have created_at, updated_at use withTimestamps()

Model Game

    public function platforms() {
        return $this->belongsToMany('\App\Models\Platform', 'game_platform')->withPivot('released_at', 'requirement_minimum', 'requirement_recommended')->withTimestamps();
    }

Model Platform


    public function games() {
        return $this->belongsToMany('\App\Models\Game', 'game_platform')->withPivot('released_at', 'requirement_minimum', 'requirement_recommended')->withTimestamps();
    }

First you need the get the platform with first then with games() you sync the args to make it work, the second argument is to detach first before inserting if false then it won't detach it just make a duplicate if there's a same row.

$platform = Platform::firstOrCreate(['slug' => $platform->platform->slug],$args);
$args_game = [
	'game_id' => $game->id,
    'platform_id' => $create->id,
    'released_at' => $platform->released_at,
    'requirement_minimum' => $platform->requirements_en->minimum ?? '',
    'requirement_recommended' => $platform->requirements_en->recommended ?? '',
];

$create->games()->sync([$args_game], true);

I still don't get why I needed to put an array inside an array in sync function... Need to drill this into my head because everytime this happens I get stuck a lot.

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe