0
votes

I am working with the laravel 5.4

I have created 3 tables:
tickets
ticket_cc_users
users.

The table ticket_cc_users works as a pivot table.

In the code below, i want to update my pivot table. However, when i run the update query, it inserts data into my database instead of updating it.

$ticket = Ticket::find($id);
$ticket->requester_id = $this->user['id'];
$ticket->type = $request->type;
$ticket->priority = $request->priority;
$ticket->subject = $request->subject;
$ticket->description = $request->description;
$ticket->status = $request->status;     
if($ticket->save())
{
    for($i=0;$i<count($request->cc_id);$i++)
    {
        $ticket->users()->attach($request->cc_id[$i]['id'],['ticket_id'=>$ticket->id]);
    }           
}

Ticket model :

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

User model :

public function tickets()
{
    return $this->belongsToMany('App\Models\Tickets\Ticket','ticket_cc_users');
}

What should i do in order to my the code do what i want?

1
Can you show the relations in your Ticket and User model?thefallen

1 Answers

1
votes

The attach() method will create a new record in your pivot table. To update an existing record:

$ticket->users()->updateExistingPivot($userID, $arrayOfColumnsYouWantToUpdate);

I'm not sure what yor $request->cc_id means, but in my example if you can set $userID to a ID of a user which you want to update and the next argument in the method updateExistingPivot() is an array of the columns in the pivot table which you want to update.

EDIT

If you want to update the users related to the ticket replace your for loop with this one:

$userIDs = [];

for($i=0;$i<count($request->cc_id);$i++)
{
    $userIDs[] = $request->cc_id[$i]['id'];
}

$ticket->users()->sync($userIDs);

The sync() method will delete all users which are no longer in your ticket and will add the new ones automatically.