How can I get the sql executed when I am saving some data? For example,
$user = New User;
$user->name = "test";
$user->mail = "[email protected]";
$user->save();
I DON'T want to execute the query. I just want to get the query string.(something like "INSERT INTO users.....")
I have tried $user->toSql();
. But it gives "select * from users" which is wrong.
toSql();
is for the model query builder. so that's why when you do $user->toSql();
you get select all statement.
you can do two things here
one, use DB::listen
DB::listen(function ($query) {
echo $query->sql;
});
$user = New User;
$user->name = "test";
$user->mail = "[email protected]";
$user->save();
two, QueryLog if you need more details.
DB::enableQueryLog();
$user = New User;
$user->name = "test";
$user->mail = "[email protected]";
$user->save();
dd(DB::getQueryLog());
if you do not want to run the query, just wrap it with DB::pretend
just like when you do migration adding --pretend
, so that you will not migrate the DB
you will get all the sql
scripts.
DB::pretend(function () {
$user = New User;
$user->name = "test";
$user->mail = "[email protected]";
$user->save();
});