Tags
Asked 3 years ago
17 Jun 2021
Views 216
Ed

Ed posted

Generate The Raw MySQL Query From Laravel Query Builder

Generate The Raw MySQL Query From Laravel Query Builder
shabi

shabi
answered Apr 27 '23 00:00

In Laravel, you can generate the raw MySQL query from the Laravel Query Builder using the toSql () method. Here's how to do it:

First, build your query using the Laravel Query Builder:



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

This query selects the id and name columns from the users table where the age is greater than 18, and orders the results by name.

Next, call the toSql () method on the query builder instance to get the raw SQL query:



$sql = $query->toSql(
);
The $sql variable now contains the raw MySQL query that was executed for the query.

You can also pass the bindings parameter to the toSql () method to get the raw SQL query with bindings:



$sql = $query->toSql();
$bindings = $query->getBindings();
$rawSql = vsprintf(str_replace('?', '%s', $sql), $bindings);

This code replaces the ? placeholders in the raw SQL query with the actual binding values, and stores the result in the $rawSql variable.

Note that the to Sql() method returns the raw SQL query as a string, but does not execute the query. To execute the query and retrieve the results, you need to call one of the query execution methods like get (), first (), or paginate ().
Post Answer