Home php How to Get Query Log in Laravel Eloquent ?

How to Get Query Log in Laravel Eloquent ?

by Shahriar Sagor
Example 1:

Now in this example i can get the directly get current sql query by using toSql() of laravel query builder. So in this example i don’t need to enable query log or something i can directly query like bellow example:

Controller Code:
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $user = User::where('id',1)->toSql();
  
        dd($user);
    }
}
Example 2:

Now in this example we must need to enable the query log by using DB::enableQueryLog() of Laravel Query builder. enableQueryLog() will give the access to store all execute query in cache and i can get that query by using DB::getQueryLog(). Now in this example i will get all query log not last only. bellow example how to use it together.

Controller Code:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use DB;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        DB::enableQueryLog();
  
        $user = User::where('id',1)->get();
  
        $query = DB::getQueryLog();
  
        dd($query);
    }
}

Example 3:

In this example i make the same as example 2, but you can get exactly last query using end(). so let’s see how to use.

Controller Code:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use DB;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        DB::enableQueryLog();
  
        $user = User::where('id',1)->get();
  
        $query = end($query);
  
        dd($query);
    }
}

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like