If using SQLite, it is useful to be able to cascade a delete to related models. For instance, if a user is deleted, all their posts should also be deleted rather than being orphaned.
In the schema for the pivot table, you specify;
$table->integer('post_id')->unsigned(); $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
This works out of the box for mysql, but with sqllite it is not supported without turning it on.
I had this issue, and created a workaround, but I’m not comfortable with the solution because it required me to change the Laravel source. I’m only a newbie so could not really see an ‘app’ way of doing it.
In config/database.php
'sqlite' => [ 'driver' => 'sqlite', 'database' => storage_path().'/database2.sqlite', 'prefix' => '', 'exec' => 'PRAGMA foreign_keys = ON;', //enable delete cascade ],
I added a new element ‘exec’
Then in /vendor/laravel/framework/src/Illuminate/Database/Connectors/SQLiteConnector.php, replace;
return $this->createConnection("sqlite:{$path}", $config, $options);
with
$pdo=$this->createConnection("sqlite:{$path}", $config, $options); //any exec statement? $exec = array_get($config, 'exec'); if(isset($exec)) { $pdo->exec($exec); } return $pdo;
This allows the foreign_keys property to be set each time the connection is opened, and also any additional exec statements that might be needed.
Hello,
I found this solution on StackOverflow : http://stackoverflow.com/questions/31228950/laravel-5-1-enable-sqlite-foreign-key-constraints
To summarize (in case the link doesn’t work), you can activate the foreign keys and cascades in SqLite from the AppServiceProvider.
Just add this in the boot method in App\Providers\AppServiceProvider class.
if (DB::connection() instanceof \Illuminate\Database\SQLiteConnection) {
DB::statement(DB::raw('PRAGMA foreign_keys=1'));
}
Thanks Frédéric
Thats a good way to keep changes out of the framework.
I’ve not tested it, but it looks ok.