Get the Query Executed in Laravel 3/4

2020-01-24 10:30发布

How can I retrieve the raw executed SQL query in Laravel 3/4 using Laravel Query Builder or Eloquent ORM?

For example, something like this:

DB::table('users')->where_status(1)->get();

Or:

(posts (id, user_id, ...))

User::find(1)->posts->get();

Otherwise, at the very least how can I save all queries executed to laravel.log?

20条回答
Evening l夕情丶
2楼-- · 2020-01-24 10:49

The Loic Sharma SQL profiler does support Laravel 4, I just installed it. The instructions are listed here. The steps are the following:

  1. Add "loic-sharma/profiler": "1.1.*" in the require section in composer.json
  2. Perform self-update => php composer.phar self-update in the console.
  3. Perform composer update => php composer.phar update loic-sharma/profiler in the console as well `
  4. Add 'Profiler\ProfilerServiceProvider', in the provider array in app.php
  5. Add 'Profiler' => 'Profiler\Facades\Profiler', in the aliasses array in app.php as well
  6. Run php artisan config:publish loic-sharma/profiler in the console
查看更多
迷人小祖宗
3楼-- · 2020-01-24 10:50

You can also listen for query events using this:

DB::listen(function($sql, $bindings, $time)
{
    var_dump($sql);
});

See the information from the docs here under Listening For Query Events

查看更多
爷的心禁止访问
4楼-- · 2020-01-24 10:50

To get the last executed query in laravel,We will use DB::getQueryLog() function of laravel it return all executed queries. To get last query we will use end() function which return last executed query.

$student = DB::table('student')->get();
$query = DB::getQueryLog();
$lastQuery = end($query);
print_r($lastQuery);

I have taken reference from http://www.tutsway.com/how-to-get-the-last-executed-query-in-laravel.php.

查看更多
叛逆
5楼-- · 2020-01-24 10:51
Event::listen('illuminate.query', function($sql, $param)
{
    \Log::info($sql . ", with[" . join(',', $param) ."]<br>\n");
});

put it in global.php it will log your sql query.

查看更多
狗以群分
6楼-- · 2020-01-24 10:51

There is very easy way to do it, from your laravel query just rename any column name, it will show you an error with your query.. :)

查看更多
仙女界的扛把子
7楼-- · 2020-01-24 10:53

Laravel 3

Another way to do this is:

#config/database.php

'profiler' => true

For all Queries result:

print_r(DB::profiler());

For last Result:

print_r(DB::last_query());
查看更多
登录 后发表回答