Laravel 5 Eloquent: How to get raw sql that is being executed? (with binded data)

前端 未结 5 1635
栀梦
栀梦 2021-02-06 01:13

Im trying to figure out how to get the raw sql query being executed including the binded data in it. Here is what ive got:

\\DB::connection()->enableQueryLog(         


        
相关标签:
5条回答
  • 2021-02-06 01:22

    Add this function to your application and simply call.

    function getQuery($sql){
            $query = str_replace(array('?'), array('\'%s\''), $sql->toSql());
            $query = vsprintf($query, $sql->getBindings());     
            return $query;
    }
    $foo = Foo::where('bar', 'baz');
    print_r(getQuery($foo));
    

    Output: select * from Foo where bar = 'baz'

    0 讨论(0)
  • 2021-02-06 01:22

    Try to add event listener for query :

    Event::listen('illuminate.query', function($query)
    {
        var_dump($query);
    });
    

    or

    $results = User::where('id',$id)->toSql();
    dd($results)
    
    0 讨论(0)
  • 2021-02-06 01:27

    Add this in your routes Folder :

    \Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
        Log::info( json_encode($query->sql) );
        Log::info( json_encode($query->bindings) );
        Log::info( json_encode($query->time)   );
    });
    

    Log::info() ==> will log the SQL query in your storage/logs/laravel.log file

    var_dump() ==> will display in the API call output

    0 讨论(0)
  • 2021-02-06 01:33

    Another option is to get the queries from Laravel Debugbar:

    $queries = debugbar()->getCollector('queries');  
    $statements = $queries->collect()['statements'];
    dd($statements);
    
    0 讨论(0)
  • 2021-02-06 01:41

    You may want to check out the Laravel debugbar. I wouldn't develop a Laravel app without it. It will give you a breakdown of all queries (including repeated queries and ajax queries), with the speed they executed at and a note to the line in the controller/method that called them. (It provides TONS more info as well, such as views, gates, routes, etc.)

    Also, Laravel has a toSql() method that you can use instead of your example. It will only show you the prepared statement as your example does, but it's at least a little cleaner. If you use toSql(), you have to apply it before you execute the query though.

    $foo = Foo::where('bar', 'baz');
    $foo_sql = $foo->toSql();
    $foo->get();
    
    0 讨论(0)
提交回复
热议问题