Skip to content

Instantly share code, notes, and snippets.

@coderua
Created February 5, 2016 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderua/b3f4a24db0c2a15b3db8 to your computer and use it in GitHub Desktop.
Save coderua/b3f4a24db0c2a15b3db8 to your computer and use it in GitHub Desktop.
PHP Trait for Disable/Enable foreign key checkin for different drivers in Laravel
<?php
/**
* Disable/Enable foreign key checkin for different drivers
*
* Usage:
* 1. Save the trait to app/Traits/DisablesForeignKeys.php
* 2. Add use statement in database/seeds/DatabaseSeeder.php:
* use App\Traits\DisablesForeignKeys;
* 3. Add use to class definition:
* class DatabaseSeeder extends Seeder
* {
* use DisablesForeignKeys;
* // ...
* }
* 4. For disable key checking use method:
* $this->disableForeignKeys();
* 5. For enable key checking use method:
* $this->enableForeignKeys();
*
* @version 05.02.2016 22:35
*/
namespace App\Traits;
use Illuminate\Support\Facades\DB;
trait DisablesForeignKeys
{
private $commands = [
'mysql' => [
'enable' => 'SET FOREIGN_KEY_CHECKS=1;',
'disable' => 'SET FOREIGN_KEY_CHECKS=0;',
],
'sqlite' => [
'enable' => 'PRAGMA foreign_keys = ON;',
'disable' => 'PRAGMA foreign_keys = OFF;',
],
];
/**
* Disable foreign key checks for current db driver
*/
protected function disableForeignKeys()
{
DB::statement($this->getDisableStatement());
}
/**
* Enable foreign key checks for current db driver
*/
protected function enableForeignKeys()
{
DB::statement($this->getEnableStatement());
}
/**
* Return current driver enable command
*
* @return mixed
*/
private function getEnableStatement()
{
return $this->getDriverCommands()['enable'];
}
/**
* Return current driver disable command
*
* @return mixed
*/
private function getDisableStatement()
{
return $this->getDriverCommands()['disable'];
}
/**
* Returns command array for current db driver
*
* @return mixed
*/
private function getDriverCommands()
{
return $this->commands[DB::getDriverName()];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment