Search code examples
laraveleloquentormforeign-keyssoft-delete

How to solve SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed error when recording deleted model data?


Suppose we have a project with Laravel framework and there is a scenario where we have to record/save our Product Model(for example)'s behaviour. Everything is fine while we are recording create and update actions BUT when we reach to delete action, then we can not save anything about the deleted model data!

So if we try to do save the deleted model data, we will get the following error : SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed.

So what is the solution in this kind of situations?


Solution

  • The Solution is using Soft Deletes. And here is the code example with explanation:

    • First we have to take care of the migration:

        public function up(){
            Schema::table('products', function (Blueprint $table) {
               $table->softDeletes(); 
            });
        }
      
    • Then this is how we use the soft deletes trait in our model:

       namespace App\Models;
      
       use Illuminate\Database\Eloquent\Model;
       use Illuminate\Database\Eloquent\SoftDeletes; 
       use Illuminate\Database\Eloquent\Factories\HasFactory;
      
       class Post extends Model {
      
           use HasFactory, SoftDeletes; 
      
       }
      
    • Performing soft delete is no different with the usual delete/destroy:

      $post->delete();

    • Checking the soft deleted model:

       if ( $post->trashed() ) { 
      
          // continue codes
      
       }
      
    • Writing a test for the soft deleted model(TDD):

        public function test_product_is_soft_deleted()
        { 
      
          $product = Product::factory()->create();
      
          $this->delete(route('products.destroy', $product));
      
          $this->assertSoftDeleted($product);
        }