Laravel testing with failing foreign key check on sqlite

as a firm believer in Test Driven Development (TDD), I make sure to test all of my codes. Whenever I am coding in PHP using laravel, I opt to use sqlite memory as my testing database because of the speed it gives and it is very inexpensive. Hwoever, sqlite has some shortcomings, one of which is its default lack of foreign keys. This may prove to be problematic when you are testing relationships in your models and you wish to enforce refential inetgrity..

To enable the use of foreign keys in sqlite, use the code below

add the code below into the boot method of  your AppServiceProvider.php

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s