Laravel – Simple Query Debug

Łukasz Piotrowski Comments 0

    Sometimes We must check exactly what query was generated by Eloquent or DB. Unfortunately it's not simple as we can imagine.

    The solution might be install laravel-debugbar, but if we want check only one query it's unnecessary to install it.

    I'll give You very simple solution :)


    Prepare

    Firstly we must tur on query log

    DB::enableQueryLog();

    Place it before query You want log or globally eg. on AppServiceProvider

    Magic

    Next put snippet after query:

    $queries = \DB::getQueryLog();
    foreach($queries as $key => $query) {
        $queries[$key]['raw'] = $query['query'];
        for($i=0, $counter = count($query['bindings']); $i < $counter; $i++) {
            $queries[$key]['raw'] = preg_replace('/\?/', "'".array_shift($query['bindings'])."'", $queries[$key]['raw'], 1);
        }
    }
    dd($queries);

    This part takes all runned queries and put binding into correct place.
    You can see results below.

    array:1 [
      0 => array:4 [
        "query" => "select * from `program_service_charges` where ((program_id = ? AND user_id = ? AND role_id IS NULL) OR (program_id = ? AND role_id = ? AND user_id  IS NULL) OR (program_id = ? AND user_id  IS NULL AND role_id  IS NULL)) and `service` = ? order by `user_id` desc, `role_id` desc limit 1"
        "bindings" => array:6 [
          0 => 1
          1 => 1
          2 => 1
          3 => 1
          4 => 1
          5 => "cb_mo_25"
        ]
        "time" => 1.35
        "raw" => "select * from `program_service_charges` where ((program_id = '1' AND user_id = '1' AND role_id IS NULL) OR (program_id = '1' AND role_id = '1' AND user_id  IS NULL) OR (program_id = '1' AND user_id  IS NULL AND role_id  IS NULL)) and `service` = 'cb_mo_25' order by `user_id` desc, `role_id` desc limit 1"
      ]
    ]
    Top