Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1: Enable SQLite foreign key constraints

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.

like image 532
TachyonVortex Avatar asked Jul 05 '15 09:07

TachyonVortex


People also ask

Does SQLite enforce foreign key constraints?

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.

Is there foreign key in SQLite?

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.

How do foreign keys work in SQLite?

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.

Can foreign key be null SQLite?

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.


2 Answers

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.

like image 186
TachyonVortex Avatar answered Sep 24 '22 13:09

TachyonVortex


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");
}
like image 27
vivanov Avatar answered Sep 25 '22 13:09

vivanov