DEV Community

Daniel Rodrigues
Daniel Rodrigues

Posted on • Updated on

Query Log Laravel, understanding what happens behind the “rags”.

So you’re writing some querys in Eloquent Laravel and suddenly someone asks what actually happens behind the “curtains” that involve the abstraction of your favorite Framework and you don’t know how to respond, find out how below.


knowing getQueryLog() method

This method has been available since version 4.2 of Laravel, meaning it is nothing new, but many developers are unaware. What he does is very simple; it generates a complete log with very interesting information about the behavior of a query, to use it’s simple, just look below:

<?php

namespace API\Repositories;

use API\Repositories\Contracts\WorkoutPlanRepositoryInterface;
use API\WorkoutPlan;
use Illuminate\Support\Facades\Validator;
use DB;

final class WorkoutPlanRepository
{

    public function workoutPlanByUser($id)
    {
        DB::enableQueryLog();

        $workoutPlansByUser = WorkoutPlan::with('user', 'workoutType')
            ->where('fk_user', $id)
            ->get();

        dd(DB::getQueryLog());
    }
}
Enter fullscreen mode Exit fullscreen mode
array:3 [

    0 => array:3 [
      "query" => "select * from "workout_plan" where "fk_user"=?"
      "bindings" => array:1 [
          0 => "1"
    ]
      "time" => 4.57
  ]
    1 => array:3 [
      "query" => "select * from "user" where "user"."id" in (?)"
      "bindings" => array:1 [
          0 => 1
    ]
      "time" => 3.22
  ]
    2 => array:3 [
      "query" => "select * from "workout_type" where "workout_type"."id" in (?, ?, ?)"
      "bindings" => array:3 [
          0 => 1
          1 => 2
          2 => 3
      ]
      "time" => 3.55
     ]
]
Enter fullscreen mode Exit fullscreen mode

Here we have some really important information for our application, our query was written using the Eager Loading technique through the Laravel with () method that defines the relationships that must be loaded.

The first information is the query executed, note that we are executing three querys, the second information refers to the values ​​used in the querys, in our case values ​​for the where and in clauses , and finally the time spent to “rotate” our search .

After this article you will never be “awkward” when asked what happens when such a query is executed, I hope this tip will be useful for you until the next.

Top comments (0)