How to view all database requests in Laravel5
Laravel has a set of flexible database operation solutions. This article introduces a simple method to obtain all SQL statements.
1. enable QueryLog
We need to call the following method to tell the framework to start recording SQL requests:
DB::enableQueryLog();
We can consider placing this code segment in BeforeMiddleware middleware (see this document). run the following command to generate BeforeMiddleware:
php artisan make:middleware BeforeMiddleware
The above command generates the app/Http/Middleware/BeforeMiddleware. php file, in the handle method of this file:
public function handle($request, Closure $next){ DB::enableQueryLog(); return $next($request);}
2. get QueryLog
After QueryLog is enabled, we can use the following methods to obtain the SQL statement executed:
$queries = DB::getQueryLog();
If you want to obtain all querylogs, you can place the code in AfterMiddleware.
Run the following command to create AfterMiddleware ):
php artisan make:middleware AfterMiddleware
The app/Http/Middleware/AfterMiddleware. php file is generated. in the handle method of this file:
public function handle($request, Closure $next){ $response = $next($request); //retrieve all executed queries $queries = DB::getQueryLog(); //code to save query logs in a file //return response return $response; }