Home > Net >  Delete function in Laravel
Delete function in Laravel

Time:10-04

I'm stuck in this function. I want to delete a document which has a many to many relationship between library and client. I think I'm doing something entirely wrong here.

Documents have id, id_client, id_biblio and file

I have no idea how to delete the file from the clientController

public function delete($id)
{
    $client_docs = ClientDocument::find($id);
    $client_docs->delete();

    return redirect()->back()->with('success', 'client has been Deleted');
}

CodePudding user response:

Whilst you can delete the relations first, if your foreign keys are set up to cascade deletions, you shouldn't have to.

If you have a Client, which has an ID, and that Client has one or more Documents, each of which is associated to the client through a foreign key on (for example) client_id within the Documents table, then when you set up that foreign key you have various options as to what to do with the Document when the Client is deleted.

Cascade is the one it looks like you want to use in this situation - if the Client is deleted and the relationship is set to cascade, then any Documents associated with that Client will also be deleted.

Alternatives are "restrict" which will leave the Document in place but the client_id field will not be editable, or "set null" which will leave the Document in place but set the client_id field to null. Neither of those would seem appropriate in this instance.

CodePudding user response:

Storage::disk('public')->delete($document->name); firstly you have to remove that document from storage . then get the data base id and use $delete = Document::find($id); $delete->delete();

  • Related