Content Notice!

This post is really old, and no longer reflect my skill level, views or opinions, it is made available here for archival purposes (it was originally on my old WordPress blog).

Keep that in mind when you read the contents within.

How to enable Foreign Key constraints in SQLite when writing tests in Laravel

Recently found one of my test failing due to my inmemory SQLite database not enforcing foreign key constrains.

Googled around and found a solution for it, reposting that solution here so i can easily find it in the future, and that other people can more easily find a copy-pastable solution.

Put the following code in your AppServiceProvider file within the boot() method:

if (DB::connection() instanceof \\Illuminate\\Database\\SQLiteConnection) {
    DB::statement(DB::raw('PRAGMA foreign_keys=1'));
}

Source:

https://stackoverflow.com/questions/31228950/laravel-5-1-enable-sqlite-foreign-key-constraints