<tutorialjinni.com/>

Print SQL Query in Laravel

Posted Under: Laravel, PHP, Programming, Snippets, Tutorials on Feb 26, 2020
Code Snippet to print raw SQL queries.

To print single Raw SQL Query
$query = DB::table('Users')->join('salary','a','=','c');
echo $query->toSql();
This will not show parameters in the query, because they are bonded after preparation of the query. To view them use
print_r( $query->getBindings() );
To view all this nicely use this method
public static function getEloquentSqlWithBindings($query)
{
    return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
        return is_numeric($binding) ? $binding : "'{$binding}'";
    })->toArray());
}
To print all queries executed use you need to enable enableQueryLog
DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

dd(DB::getQueryLog()); // Show results of log


imgae