Laravel Eloquent truncate - Foreign key constraint

No, this is the way your database works. You can't truncate table that is referenced by some other table. You may do something like

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
DB::table('datapoints')->truncate();
DB::table('sensors')->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

to disable foreign key checks, truncate tables and enable it again.


In Laravel 7 and 8, for compatibility across 4 databases (MySql, Postgres, SQLite and SqlServer) and no Eloquent, you can use:

Schema::disableForeignKeyConstraints();
DB::table('datapoints')->truncate();
DB::table('sensors')->truncate();
Schema::enableForeignKeyConstraints();

If you prefer to use Eloquent objects, Maksym's answer the "Eloquent" way

use Illuminate\Support\Facades\Schema;
use App\Models\Datapoint;
use App\Models\Sensor;


Schema::disableForeignKeyConstraints();
Datapoint::truncate();
Sensor::truncate();
Schema::enableForeignKeyConstraints();