Laravel Eloquent Query Log

use App\Order; public function show(Order $order){ $data = $order->all(); return dd($order->getQueryLog()); 

Is there a way to display a query created by Eloquent in Laravel?

I tried getQueryLog(); but it does not work

+19
source share
6 answers

First you need to enable the query log, this can be done using

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

then you can use the code below to view the query log

 $queries = DB::getQueryLog(); 

if you want to see the last executed request

 $last_query = end($queries); 

to learn more about registration, see https://laravel.com/docs/5.0/database#query-logging

Example

 public function show(Order $order){ \DB::connection()->enableQueryLog(); $data = $order->all(); $queries = \DB::getQueryLog(); return dd($queries); } 
+36
source

To use getQueryLog() , you need to enable it first:

 DB::enableQueryLog(); DB::getQueryLog(); 

If you want to see real queries, you can use Laravel Debugbar , it will show all real Laravel queries created during the current query.

Sometimes ->toSql() also useful.

+4
source

Works on 5.6, something like this in AppServiceProvider :: boot ()

  // Log all DB SELECT statements // @codeCoverageIgnoreStart if (!app()->environment('testing') && config('app.log_sql')) { DB::listen(function ($query) { if (preg_match('/^select/', $query->sql)) { Log::info('sql: ' . $query->sql); // Also available are $query->bindings and $query->time. } }); } 

Then in config / app.php so that it is easy to enable / disable the .env change

  'log_sql' => env('LOG_SQL'), 

All credits: https://arjunphp.com/laravel-5-5-log-eloquent-queries/

And this can be analyzed for unique queries with:

  grep ") sql:" laravel.log | sed -e "s#.*select\(.*\)\[\]#select\1#" | sort -u 
+4
source

I know this is an old question, but it can help others who had the same problem as mine.

If you are using a connection other than the default connection, you must specify it in order to correctly log query requests.

 \DB::connection('YourConnection')->enableQueryLog(); $test = MyModel::all(); $queries = \DB::connection('YourConnection')->getQueryLog(); dd($queries); 
+2
source

Use the following method to view query logs in the laravel.log file.

 namespace App\Providers; use DB; use Log; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { DB::listen(function($query) { Log::info( $query->sql, $query->bindings, $query->time ); }); } // ... } 
+1
source

You can use ::toSql() or ->toSql() as shown below:

 use App\Order; public function show(Order $order){ return $order::toSql(); 

Or

 use App\Order; public function show(Order $order){ return $order::where("id", "<>", 0)->toSql(); 

You may need to enable the query log:

 DB::enableQueryLog(); 
0
source

Source: https://habr.com/ru/post/1261258/


All Articles