Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate The Raw MySQL Query From Laravel Query Builder

Tags:

How can i get mysql query of a laravel query

Convert:

App\User::where('balance','>',0)->where(...)->get(); 

To:

SELECT * FROM users WHERE `balance`>0 and ... 
like image 608
Saeed Vaziry Avatar asked Jun 12 '17 10:06

Saeed Vaziry


People also ask

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.

What is DB :: Raw in Laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection. Since the query builder is using PDO in the background, we know there is a way to bind parameters to our query so it will sanitize the bound variables.

How do I return a query in Laravel?

The first method to get the query of an Eloquent call is by using the toSql() method. This method returns the query without running it – good if you don't want to alter data and only get the query – but this method doesn't show the whole query if your query is more complex or if there are sub-queries.


2 Answers

use toSql() method of laravel to get the query to be executed like

App\User::where('balance','>',0)->where(...)->toSql(); 

But Laravel will not show you parameters in your query, because they are bound after preparation of the query. To get the bind parameters, use this

$query=App\User::where('balance','>',0)->where(...); print_r($query->getBindings() ); 

enable the query log as DB::enableQueryLog() and then output to the screen the last queries ran you can use this,

dd(DB::getQueryLog()); 
like image 90
RAUSHAN KUMAR Avatar answered Oct 06 '22 08:10

RAUSHAN KUMAR


you can add this function to your helpers

function getRealQuery($query, $dumpIt = false) {     $params = array_map(function ($item) {         return "'{$item}'";     }, $query->getBindings());     $result = str_replace_array('\?', $params, $query->toSql());     if ($dumpIt) {         dd($result);     }     return $result; } 

and use like this:

getRealQuery(App\User::where('balance','>',0)->where(...),true) 
like image 34
Honarkhah Avatar answered Oct 06 '22 07:10

Honarkhah