A quick way to display a SQL query in tinker

A quick way to display a SQL query in tinker

Feb 5, 2017,

All Laravel applications include Tinker, a REPL powered by the PsySH package. Tinker allows you to interact with your entire Laravel application on the command line, including the Eloquent ORM, jobs, events, and more. To enter the Tinker environment, run the tinker Artisan command:

php artisan tinker

Ok, now let's add an event listener:

>>> DB::listen(function ($query) { dump($query->sql); dump($query->bindings); dump($query->time); });

That's all. Now all queries will be displayed in this session.

>>> App\User::first();
"select * from `users` limit 1"
[]
15.84
=> App\User {#679
     id: 1,
     name: "Prof. Vincent Upton",
     email: "sbayer@example.net",
     created_at: "2017-01-29 15:03:20",
     updated_at: "2017-01-29 15:03:20",
   }

Another example - select() overrides previous one

>>> App\User::select('name')->select('email')->where('email', 'like', '%@example%')->where('name', 'like', '%Vincent%')->get();
"select `email` from `users` where `email` like ? and `name` like ?"
array:2 [
  0 => "%@example%"
  1 => "%Vincent%"
]
0.97
=> Illuminate\Database\Eloquent\Collection {#712
     all: [
       App\User {#713
         email: "sbayer@example.net",
       },
     ],
   }