Tags
Asked 2 years ago
17 Jun 2021
Views 192
Ardith

Ardith posted

Laravel how to get query with bindings?

Laravel how to get query with bindings?
noob

noob
answered Apr 27 '23 00:00

In Laravel, you can get the SQL query with bindings using the toSql () and getBindings () methods on the query builder object. Here's an example:



$query = DB::table('users')
            ->select('name', 'email')
            ->where('age', '>', 18);

$sql = $query->toSql();
$bindings = $query->getBindings();

echo $sql; // Outputs the SQL query with placeholders for bindings
echo "<br>";
print_r($bindings); // Outputs an array of binding values

In this example, we create a query builder object by calling the DB::table() method with the table name, and then we chain the select() and where() methods to define the query.

To get the SQL query with bindings, we call the toSql() method on the query builder object, which returns the SQL query with placeholders for the bindings. We also call the getBindings() method to get an array of the binding values.

Finally, we output the SQL query and the array of bindings using echo and print_r().

Note that this method only works for select statements. For other types of queries such as inserts, updates, and deletes, you can use the insert() , update(), and delete() methods respectively, and then call toSql() and getBindings() on the resulting query builder object.
Post Answer