PASSWORD RESET

Your destination for complete Tech news

how to get a query with bindings in Laravel eloquent?

2.42K 0
< 1 min read

In Laravel, you can use the toSql method of a query builder or an Eloquent model to get the raw SQL query with the bound parameters as placeholders.

For example, suppose you have a User model and you want to get the raw SQL query for a SELECT statement that filters users by their name. You can use the following code:

$users = User::where('name', 'like', '%John%')->get();

$rawSql = $users->toSql();
$bindings = $users->getBindings();

dd($rawSql, $bindings);

This will output the raw SQL query and the array of bindings, like this:

"select * from `users` where `name` like ?", ["%John%"]

You can then use the DB::raw method to interpolate the bindings into the raw SQL query, like this:

$interpolatedSql = DB::raw(vsprintf($rawSql, $bindings));

This will produce a string containing the final SQL query with the bindings interpolated into the placeholders.

Note that this method only works for simple queries that do not use subqueries or advanced clauses. For more complex queries, you may need to manually build the query and bind the parameters using the DB facade or the DB::connection method.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.