How do I display query log in Laravel

Published January 19, 2022

In this tutorial, we'll look at how to display a query log in Laravel. Let's have a look at the steps below:

Step 1: Create a new Laravel project using the following command

composer create-project --prefer-dist laravel/laravel Querylog

 

Laravel get Query Log php

 

A new project will be created in your htdocs folder

 

Laravel get Query Log php 2

 

Step 2:  Create a new database using the SQL query below: CREATE DATABASE blog;

Create a database table named users, with columns for id, name, and address, and populate it with sample data

 

Laravel get Query Log php3

 

Step 3: Open your .env file and configure your database to connect your laravel application with the database.  Set your DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD

 

Step 4: Let's create a userController.php using the command

  • php artisan make: controller UserController

 

Laravel get Query Log php 4

 

Paste the code below in your userController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

//import database class

use Illuminate\Support\Facades\DB;

class UserController extends Controller

{

    //

    function index()

 { DB::enableQueryLog(); // to enable query log

  $query = DB::select("SELECT * FROM  users");

         $bb = DB::getQueryLog(); // get query logs from cache

       $a= dd($bb);

   return $query;

    }

}

 

In this code, we have implemented DB::getQueryLog(); to get the query log from the cache

Step 5:  Now, open your webb.php file and paste the following code

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

 

Route::get('/', function () {

    return view('welcome');

});

Route::get('users', [UserController::class,'index']);

 

Step 6: To acquire the application url, use the command php artisan serve. Our query log is now public

Laravel get Query Log php5

We covered in this laravel tutorial example how to display a query log in Laravel

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

672 Views