skip to Main Content

I make test in Laravel, and I want to truncate all users, and create only one. This code show me error SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint. What can I do that truncate users ? Just I don’t want to use solutions that violate database settings, e.g.Schema::disableForeignKeyConstraints();

 public function test_delete_user()
    {
 
        DB::table('users')->truncate();
        $role = User::factory()->create();
     .......
        
    }

3

Answers


  1. "I am currently facing the same issue"

    Login or Signup to reply.
  2. Your table user have a forign key constraint remove that to get truncate working.

    Can i see the database schema.

    ALTER TABLE table_name 
    DROP FOREIGN KEY constraint_name;
    

    This is for MysQl try that on your table

    Login or Signup to reply.
  3. Before using

    DB::table('users')->truncate();
    

    You may try to use (suppose your foreign table name "addresses")

    DB::statement('ALTER TABLE addresses DROP FOREIGN KEY addresses_user_id_foreign');
    

    It may help you.
    Then it may look like

    public function test_delete_user()
        {
            DB::statement('ALTER TABLE addresses DROP FOREIGN KEY addresses_user_id_foreign');
     
            DB::table('users')->truncate();
            $role = User::factory()->create();
         .......
            
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search