Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the save query in Laravel?

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.

like image 550
Nabil Farhan Avatar asked Aug 31 '25 10:08

Nabil Farhan


1 Answers

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();
    });
like image 159
Andy Song Avatar answered Sep 03 '25 00:09

Andy Song