Laravel 5 Pivot table only saving first record

I have a table that simply has the ids of other two tables, I want an n:m relationship but right now everytime I save a record it deletes the previous one if one of the two ids was already used.

My migration:

    Schema::create('show_user', function(Blueprint $table) {
        $table->integer('show_id')->unsigned()->index();
        $table->foreign('show_id')->references('id')->on('shows');
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users');
    });

My Models:

USER

public function shows()
{
    return $this->belongsToMany('App\Show');
}

SHOWS

public function users()
{
    return $this->belongsToMany('App\User');
}

And this is how I save to the pivot table:

User::find($userid)->shows()->sync([$showid, $userid])

when I do this for user 1 (me), on show 5, it saves 1 and 5, when I try again for the same user on show 12, it saves 1 and 12 and deletes the 1 and 5 record from before. If I insert manually via phpMyAdmin I can add multiple records, but not using sync. I have tried also this, to the same result:

User::find($userid)->shows()->sync([$showid])

Answers


You are not using sync() correctly. sync() is used to add and remove Shows from a User, and expects an array of Show ids. So if you call sync([1,5]) you are adding the Shows with ids of 1 and 5 to the User and removing all other Shows previously associated with that User.

You can read about inserting related-models in Laravel here, but you probably only need to know these three examples:

If User has relationships with Shows 3, 4, and 8, and you wanted to make sure that User only had relationships with Shows 4 and 5 you would do this:

User::find($userid)->shows()->sync([4,5]); // Removes 3 and 8; Adds 5

If User already has a relationship with Show 4 and you want to add Show 5 you would do this:

User::find($userid)->shows()->attach(5); // Adds 5

If User has relationships with Shows 3, 4, 5 and 8 and you want to remove 3 and 8 you would do this:

User::find($userid)->shows()->detach([3,8]); // Removes 3 and 8

After each of these examples, User would only have relationships with Shows 4 and 5.


Need Your Help

Allow asp.net sqlmembership users to create "subusers"

asp.net entity-framework sqlmembershipprovider

I've tried searching this for days and can't seem to find an adequate answer so I'll ask here.

DataGridView selected cell style

c# winforms

How can I change the "selection style" on a DataGridView (winforms)?