Get the Query Executed in Laravel 3/4

175,080

Solution 1

Laravel 4+

Note for Laravel 5 users: You'll need to call DB::enableQueryLog() before executing the query. Either just above the line that runs the query or inside a middleware.

In Laravel 4 and later, you have to call DB::getQueryLog() to get all ran queries.

$queries = DB::getQueryLog();
$last_query = end($queries);

Or you can download a profiler package. I'd recommend barryvdh/laravel-debugbar, which is pretty neat. You can read for instructions on how to install in their repository.


Laravel 3

In Laravel 3, you can get the last executed query from an Eloquent model calling the static method last_query on the DB class.

DB::last_query();

This, however, requires that you enable the profiler option in application/config/database.php. Alternatively you could, as @dualed mentioned, enable the profiler option, in application/config/application.php or call DB::profile() to get all queries ran in the current request and their execution time.

Solution 2

You can enable the "Profiler" in Laravel 3 by setting

'profiler' => true,

In your application/config/application.php and application/config/database.php

This enables a bar at the bottom of each page. One of its features is listing the executed queries and how long each one took.

enter image description here

Solution 3

For Eloquent you can just do:

$result->getQuery()->toSql();

But you need to remove the "->get()" part from your query.

Solution 4

I would recommend using the Chrome extension Clockwork with the Laravel package https://github.com/itsgoingd/clockwork. It's easy to install and use.

Clockwork is a Chrome extension for PHP development, extending Developer Tools with a new panel providing all kinds of information useful for debugging and profiling your PHP scripts, including information on request, headers, GET and POST data, cookies, session data, database queries, routes, visualisation of application runtime and more. Clockwork includes out of the box support for Laravel 4 and Slim 2 based applications, you can add support for any other or custom framework via an extensible API.

enter image description here

Solution 5

Since the profiler is not yet out in Laravel 4, I've created this helper function to see the SQL being generated:


    public static function q($all = true) 
    {
        $queries = DB::getQueryLog();

        if($all == false) {
            $last_query = end($queries);
            return $last_query;
        }

        return $queries;
    }

NOTE: Set the $all flag to false if you only want the last SQL query.

I keep this sort of functions in a class called DBH.php (short for Database Helper) so I can call it from anywhere like this:

dd(DBH::q()); 

Here is the output I get: enter image description here

In case you are wondering, I use Kint for the dd() formatting. http://raveren.github.io/kint/

Share:
175,080

Related videos on Youtube

Patrick Maciel
Author by

Patrick Maciel

Expert PHP Developer At work (Lead Developer) Full Stack Developer (Frontend/Backend) Primary language: PHP (Laravel) Studying Vue.js, Node.js, Rails and Flutter At home Collaborate with Stack Overflow community Keep studying PHP Studying Ruby and Rails Keep look of updated and new technologies I like Creating a web/mobile solution for a manual work/process (automate) Start new projects from scratch (planning, diagramming and coding) Study new languages/technologies I love God, Jesus and Holy Spirit My fiancée <3

Updated on July 11, 2021

Comments

  • Patrick Maciel
    Patrick Maciel almost 3 years

    How can I retrieve the raw executed SQL query in Laravel 3/4 using Laravel Query Builder or Eloquent ORM?

    For example, something like this:

    DB::table('users')->where_status(1)->get();
    

    Or:

    (posts (id, user_id, ...))
    
    User::find(1)->posts->get();
    

    Otherwise, at the very least how can I save all queries executed to laravel.log?

  • duality_
    duality_ over 11 years
    Note that in Laravel 4, the Profiler is not included, you have to install it by yourself (e.g. using composer). See this SO question.
  • duality_
    duality_ over 11 years
    Your code for Laravel 4 doesn't work. I get this ErrorException: Warning: call_user_func_array() expects parameter 1 to be a valid callback, class Illuminate\Database\MySqlConnection does not have a method getQueryList.
  • rmobis
    rmobis over 11 years
    My bad, the correct method is getQueryLog. Fixed it now. Thanks!
  • Aditya M P
    Aditya M P about 11 years
    Strange... I get last_query() is not defined on the Query object error. I am just calling on an uninstantiated Eloquent model.
  • Dan Smart
    Dan Smart about 11 years
    For Laravel 3 it's actually DB::last_query(); You also need to set 'profile' to true in your application/config/database.php
  • Abishek
    Abishek about 11 years
    This doesn't seem to work for an Eloquent Model on L4. When I execute Model::find($id) and perform DB::getQueryLog() return blank array(). Any idea how to get the queries for an Eloquent Model?
  • duality_
    duality_ over 10 years
    It's discussed in the first answer there.
  • Stefan
    Stefan about 10 years
    dd(end(DB::getQueryLog()));
  • Jaak Kütt
    Jaak Kütt about 9 years
    Your answer does not seem to contribute any new knowledge to what the accepted answer by Raphael_ already covers.
  • mydoglixu
    mydoglixu about 9 years
    I think you would need "" around the {{ json_encode... }} part
  • rmobis
    rmobis almost 9 years
    @mydoglixu Since DB::getQueryLog() returns an array, there's no need to surround it with "". json_encode will translate it accordingly.
  • mydoglixu
    mydoglixu almost 9 years
    @mobis - I meant that you need the "" outside the {{ ... }} so that javascript doesn't throw an error. like this: var queries = "json output";
  • rmobis
    rmobis almost 9 years
    @mydoglixu You don't, because a JSON array (or object) is valid JavaScript. It would break if you did.
  • mydoglixu
    mydoglixu almost 9 years
    @mobis - oh yeah, duh
  • toesslab
    toesslab over 8 years
    if($all == false)? Why not simply if(!$all)
  • Kamil Kiełczewski
    Kamil Kiełczewski almost 8 years
    L4 oneliner: $q=\DB::getQueryLog();dd(end($q));
  • rmobis
    rmobis almost 8 years
    @KamilKiełczewski isn't that just a longer version of MECU's answer? I really don't see the point.
  • Kamil Kiełczewski
    Kamil Kiełczewski almost 8 years
    @rmobis MECU answer dont work in my L4 project - this is why i put my version. May be MECU answer work on L3 or L5 (?)
  • rmobis
    rmobis almost 8 years
    @KamilKiełczewski he just forgot the \ before DB::getQueryLog(). Apart from that, the two are identical.
  • Kamil Kiełczewski
    Kamil Kiełczewski almost 8 years
    @rmobis - no i have different error - try yourself. there was a problem with end(here_must_be_veraiable_not_function)
  • rmobis
    rmobis almost 8 years
    @KamilKiełczewski Oh, you're right. It's because end's argument is passed by reference so it has to be an actual variable. Good catch.
  • Kamil Kiełczewski
    Kamil Kiełczewski almost 8 years
    @rmobis ok so please give point to my comment with oneliner to be better visible to other people :)
  • qwertzman
    qwertzman over 6 years
    in Laravel 3 long queries are truncated, any idea?
  • instead
    instead about 6 years
    Quick hacky way. Not to useful in production, but in development mode it's fine in some cases.
  • Jovylle
    Jovylle almost 3 years
    I am getting to be a regular visitor of this page.