I have some query that I need to pass to another query using query builder
$query = DB::table('table')->whereIn('some_field', [1,2,30])->toSql(); Model::join(DB::raw("({$query}) as table"), function($join) { $join->on('model.id', '=', 'table.id'); })
which should results with
Select * from model join (select * from table where some_field in (1,2,30)) as table on model.id = table.id
but the bindings are not passed, which force me to do
$query = DB::table('table')->whereRaw('some_field in ('. join(',', [1,2,30]) .')')->toSql();
what can be unsafe at times. How can I get the query with bindings?
Using laravel query log we can print the entire query with params as well. In this type of debugging query is executed and we will get the complete parsed query. Here we used DB::enableQueryLog to enable the query log and DB::getQueryLog() to print the all queries in between of it.
If you write your query in Tinkerwell anyway, you can highlight the Eloquent query and press Cmd+Shift+R (or Ctrl+Shift+R if you are on Windows) and Tinkerwell profiles the query directly in the editor. You see all executed queries, the time that the query run, the memory consumption and even the peak for your memory.
DB::QueryLog() works only after you execute the query using $builder->get() . If you want to get the raw query before or without executing the query, you can use the $builder->toSql() method.
Check out the getBindings()
method on the Builder
class
getBindings()
$query = DB::table('table')->whereIn('some_field', [1,2,30]); $sql = $query->toSql(); $bindings = $query->getBindings();
Laravel now offers debugging directly on your Builder!!!
https://laravel.com/docs/queries#debugging
\App\User::where('age', '18')->dump(); \App\User::where('age', '18')->dd();
Outputs
"select * from `users` where `age` = ?" [ 0 => "18" ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With