In this article, I show you both options of printing and logging queries that help to view the queries in your Laravel application.
While developing a projects, sometimes we may come across a situation where you need to see if the written query is correct or not.
if you are logging the queries then it will help to debug the issue. Let’s see first printing queries in Laravel.
How to Print Query in Laravel?
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller { public function list(){ DB::enableQueryLog(); $students=Student::all(); dd(DB::getQueryLog()); } }
Now, if i run the code i will have the select query printed. Using the above technique, you can also print the queries executed through Eloquent.
Log Query in Laravel
It is a more easy and right way for me. Only need to add some code in the AppServiceProvider.php and done.
Open the AppServiceProvider.php file, and add 2 Facades for ‘File’ and ‘DB’ as below lines.
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;
Next, in the boot() method write the below code that will listen to each SQL query executed and log them in the storage/logs/query.log.
public function boot() { DB::listen(function($query) { File::append( storage_path('/logs/query.log'), $query->sql . ' [' . implode(', ', $query->bindings) . ']' . PHP_EOL ); }); }
\DB::listen(function($sql) { \Log::info($sql->sql); \Log::info($sql->bindings); \Log::info($sql->time); });