How to enable query log in Laravel ?

devquora
devquora

Posted On: Apr 19, 2024

 

    1 Answer Written

  •  devquora
    Answered by Priyag Chaudhary

    So you want to log an executed query in Laravel. here we are going to see different ways to enable query log in Laravel.

    1. Printing last executed query.

    You can use DB::getQueryLog() method to log or print the last executed query in Laravel. Here is an example

    DB::enableQueryLog(); // enable query log
    $posts = DB::table('post')->select('id', 'title','body')->get(); // runing query in laravel
    dd(DB::getQueryLog()); // Getting query log and printing it.
    

    2. Logging all queries in Laravel.

    If you are looking for a solution to log all queries in Laravel then you have to add following lines of code in your AppServiceProvider.php. AppServiceProvider.php is located app\Providers directory of your Laravel application.

    if(env('APP_DEBUG')){
      DB::listen(function ($query){
        File::append( storage_path('logs/queries-'.Carbon::today()->toDateString().'.log'),
          '/'.Request::path() . ' ### (' . $query->sql . ') [' . implode(', ', $query->bindings) . ']' . ' - at ' . Carbon::now()->toTimeString() . PHP_EOL
        );
      });
    }
    
    

Related Questions

Please Login or Register to leave a response.

Related Questions

Laravel Interview Questions

What is Laravel?

Laravel is a free open source "PHP framework" based on the MVC design pattern. It is created by Taylor Otwell...