Home » Php » php – Disabling MySQL Strict Mode only for one query Laravel 5.6

php – Disabling MySQL Strict Mode only for one query Laravel 5.6

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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();

Answer:

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');

}

Answer:

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'");

Answer:

In config/database.php, do as like:

‘connections’ => [

    'mysql' => [

        // Behave like MySQL 5.6

        'strict' => false,

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

]