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
.
Here's one solution. In the
boot()
method ofApp\Providers\AppServiceProvider
, add:Thanks to @RobertTrzebinski for this blog post regarding Laravel 4.
You could also activate foreign keys on a per test (file) basis, when the tests actually depend on tables with foreign keys.
Here's a trait: (e.g.
tests/ForeignKeys.php
)don't forget to run the method somewhere in your test set-up chain. I added mine as an override to my TestCase: (
tests/TestCase.php
)after that you can add it to your tests like so:
For me using a the facade DB within App\Providers\AppServiceProvider in Laravel 5.2 produced error. Here is my solution:
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:This works like a charm :-)