Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling MySQL Strict Mode only for one query Laravel 5.6

I want to disable MySQL strict mode only for one query inside a controller not for whole laravel application,

I know the risks of disabling MySQL strict mode so I don't want to disable it for my whole application from config/database.php,

I am facing problem with only one query in my whole application, so I want to disable it inside my controller before running that query only for one time!

Please help me is there any way for given situation.

like image 491
Mȍhǟmmǟd Șamȋm Avatar asked Jul 26 '18 08:07

Mȍhǟmmǟd Șamȋm


2 Answers

Changing the strict mode in runtime

config()->set('database.connections.mysql.strict', false);
\DB::reconnect(); //important as the existing connection if any would be in strict mode
Model::select()->get(); // your query called in non strict mode

//now changing back the strict ON
config()->set('database.connections.mysql.strict', true);
\DB::reconnect();
like image 107
Max Gaurav Avatar answered Nov 19 '22 16:11

Max Gaurav


Use this for MySQL ≤5.7 (taken from here):

DB::statement("set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");
// your query
DB::statement("set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");
like image 4
Jonas Staudenmeir Avatar answered Nov 19 '22 18:11

Jonas Staudenmeir