11

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.

Mȍhǟmmǟd Șamȋm
  • 261
  • 1
  • 4
  • 14

4 Answers4

17

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();
Max Gaurav
  • 1,835
  • 2
  • 13
  • 26
  • 3
    Although it works, disconnecting will break any transaction involved. Works only if your query is not part of a transaction. USE WITH CAUTION. – John Smith Apr 17 '22 at 00:18
  • Excellent, save my code after 5hours find the solution. Thanks. – Sylar Oct 12 '22 at 13:18
5

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'");
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
3

One thing tha you can do is to change this value at run time

public function doQueryWithoutStrictMode{
    config('database.connections.mysql.strict', false);
    DB::select('The query you want to make, and that should work!');

    And then, if you later want to do another query in strict mode withing the same 
    method you can enable it like this.

    config('database.connections.mysql.strict', true);

    DB::select('your other query with strict mode');

}
jarguez01
  • 194
  • 1
  • 7
2

In config/database.php, do as like:

'connections' => [

    'mysql' => [

        // Behave like MySQL 5.6

        'strict' => false,

        // Behave like MySQL 5.7
        'strict' => true,
    ]

]