laravel show query code example

Example 1: print query statement in laravel

DB::enableQueryLog();
$users = User::select("*")->get();
$quries = DB::getQueryLog();
dd($quries);
DB::table('users')->toSql();
dd($query);

Example 2: print last sql query laravel

DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

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

Example 3: show query in laravel

Use the toSql() method on a QueryBuilder instance.

DB::table('users')->toSql()

Example 4: laravel get query in normal sql without bindings

/**
 * Combines SQL and its bindings
 *
 * @param \Eloquent $query
 * @return string
 */
public static function getEloquentSqlWithBindings($query)
{
    return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
        $binding = addslashes($binding);
        return is_numeric($binding) ? $binding : "'{$binding}'";
    })->toArray());
}

Tags:

Php Example