Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel how to get query with bindings?

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?

like image 922
Mateusz Nowak Avatar asked Dec 05 '14 11:12

Mateusz Nowak


People also ask

How do I print a query in laravel 8?

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.

How do you find an eloquent query?

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.

How do I get the query builder to output its raw SQL query as a string?

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.


2 Answers

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(); 
like image 116
Douglas.Sesar Avatar answered Sep 28 '22 03:09

Douglas.Sesar


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" ] 
like image 45
Andrew Brown Avatar answered Sep 28 '22 03:09

Andrew Brown