In SQLite, foreign key constraints are disabled by default.
What's the best way to configure Laravel 5.1's SQLite database connection to enable foreign key constraints? I don't see a way of doing this in
['connections']['sqlite']
in
/config/database.php
.
SQLite has supported foreign key constraint since version 3.6. 19. The SQLite library must also be compiled with neither SQLITE_OMIT_FOREIGN_KEY nor SQLITE_OMIT_TRIGGER.
SQLite Foreign Key is used to specify that values in one table also appear in another table. It enforces referential integrity within SQLite database. The referenced table is known as parent table while the table with the foreign key is known as child table.
A foreign key is a way to enforce referential integrity within your SQLite database. A foreign key means that values in one table must also appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table.
The foreign key constraint is satisfied if for each row in the child table either one or more of the child key columns are NULL, or there exists a row in the parent table for which each parent key column contains a value equal to the value in its associated child key column.
Here's one solution. In the
boot()
method of
App\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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With