When using SQLite for in-memory tests, I discovered that foreign keys are not used by default. Not so bad until you test cascading deletes and cry rivers of ones and zeros… Do I really have to make a test database?! I thought this was America! WHHHYYYYYYYYYYY?!?!?!?!?!?!
With a bunch of Googling I found that it is possible to enable foreign keys in SQLite. They are just turned off by default to cause sadness and confusion. To enable, you can use the code below.
if (DB::connection() instanceof Illuminate\Database\SQLiteConnection) {
DB::statement(DB::raw('PRAGMA foreign_keys=1'));
}
But where to put it? I don’t want that thing chilling in my app. I only need it for testing at the moment. I extend the TestCase class for all my tests so I dropped it in the createApplication method like so:
abstract class TestCase extends Illuminate\Foundation\Testing\TestCase
{
protected $baseUrl = 'http://localhost';
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
// when using sqlite, allow foreign keys
if (DB::connection() instanceof Illuminate\Database\SQLiteConnection) {
DB::statement(DB::raw('PRAGMA foreign_keys=1'));
}
return $app;
}
}
I hope that helps someone. Here’s one of the articles that I pulled code from.