Laravel 5.1: Enable SQLite foreign key constraints Laravel 5.1: Enable SQLite foreign key constraints sqlite sqlite

Laravel 5.1: Enable SQLite foreign key constraints


Here's one solution. In theboot() method ofApp\Providers\AppServiceProvider, add:

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

Thanks to @RobertTrzebinski for this blog post regarding Laravel 4.


For me using a the facade DB within App\Providers\AppServiceProvider in Laravel 5.2 produced error.Here is my solution:

if(config('database.default') == 'sqlite'){    $db = app()->make('db');    $db->connection()->getPdo()->exec("pragma foreign_keys=1");}


Since I only want to use this in my tests, but in all tests, I ended up with a simple implementation in the Tests\TestCase class like this:

 abstract class TestCase extends BaseTestCase {        use CreatesApplication;        protected function setUp()        {            parent::setUp();            $this->enableForeignKeys();        }        /**         * Enables foreign keys.         *         * @return void         */        public function enableForeignKeys()        {            $db = app()->make('db');            $db->getSchemaBuilder()->enableForeignKeyConstraints();        }}

This works like a charm :-)