Home > Back-end >  SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed. Cannot delete rec
SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed. Cannot delete rec

Time:08-01

I'm trying to delete record from my "files" table. Here's the migration code:

public function up()
{
    Schema::create('files', function (Blueprint $table) {
        $table->id();
        $table->string('name');      // path to folder in storage and random generated name
        $table->string('visname');  // visible name
        $table->timestamps();
    });
}

and

public function up()
{
    Schema::table('files', function (Blueprint $table) {
        $table->unsignedBigInteger('folder_id')->after('visname');
        $table->unsignedBigInteger('author')->after('folder_id');
        $table->unsignedBigInteger('project_id')->after('project_id');
    
        $table->foreign('folder_id')->references('id')->on('folders');
        $table->foreign('author')->references('id')->on('users');
        $table->foreign('project_id')->references('id')->on('projects');
    });
}

I'm using javascript to delete a record.

function deleteFile(id) {
    var Req = new XMLHttpRequest();
    var form = new FormData();
    form.append('fileId', id);
    Req.open("POST", "{{ route('deleteFile') }}")
    Req.setRequestHeader('X-CSRF-TOKEN', '{{csrf_token()}}');
    Req.onload = function (oEvent) {
        $(".file" id).remove();
        console.log("Deleted");
    }
    Req.send(form);
}

And here is my controller

public function deleteFile(Request $request)
{
    $file = File::find($request->fileId);
    $file->delete();

    return response()->json([
        'success' => 400
    ]);
}

Now when I try to delete file I'm getting error said in my question. Laravel generates query, for example delete from "files" where "id" = 2

What's weird is that file in storage is deleted but database record stays intact.

CodePudding user response:

I think the problem is in your other table schema. Most probably on some other table/schema you are using file_id as a foreign key. Make sure to add constraints on your other tables. One solution could be using cascadeOnDelete() or nullOnDelete(). What is happening here is when you are trying to delete the file here it is not letting you do so as it is referenced in some other table.

You can find more details here. Larave Foreign Key Constraints

  • Related