0
votes

Can't figure out how to delete record from pivot table.

I have users that belongsToMany documents with pivot document_user table.

here is my attach method:

public function share(Request $request, $company_id, $id)
{
    $document = Document::find($id);
    $user = $request['user'];
    $document->users()->attach($user);
    flash('Document has been shared!');
    return back();
}

But how to make detach function? Should I build a form for this and what function should be? Something like $document->users()-detach($user). I have tried this, but doesn't work

1
$user is user id or user model? - iamab.in

1 Answers

1
votes

You can do this in a couple ways:

First, you can use the detach() functionality (requires a second function in your controller). An example using a similar format to the one you provided:

public function unshare(Request $request, $id)
{
    $document = Document::findOrFail($id);
    $userId = $request['user']; //Assuming this is the User ID
    $user = User::findOrFail($userId);
    $user->documents()->detach($document->id);
    flash('Document has been detached!');
    return back();
}

Second, you can create a single function that toggles the association. Essentially you send a Document ID and if it is already associated to the User then it is Detached, if it is NOT associated to the User then it will Attach.

public function share(Request $request, $id)
{
    $document = Document::findOrFail($id);
    $userId = $request['user']; //Assuming this is the User ID
    $user = User::findOrFail($userId);
    $user->documents()->toggle($document->id); //This can also be an array of IDs
    flash('Document has been toggled!'); //You might want to pass something or look up the association if you want custom messaging for attach or detach
    return back();
}

Hope this helps!