How to see AJAX query behind list view in Backpack?

471 Views Asked by At

Is it possible in Backpack 4.1 to view the actual query that is run behind a list view, the query that is AJAXed? Would be useful for debugging purposes.

1

There are 1 best solutions below

1
On BEST ANSWER

Having a look at the query builder object being used is pretty trivial, you can get it in a controller via $this->crud->query. However, getting the actual query that will be run on your DB with the PDO bindings in place for any where clauses that might be applied etc will take a little bit of setup.

You should be able to do this:

1) Make a file like app/Helpers/Database.php with this content:

if (! function_exists('asSql')) {
    /**
     * Combines SQL and its bindings
     *
     * @param \Eloquent | \Illuminate\Database\Eloquent\Builder | \Illuminate\Database\Query\Builder $query
     * @return string
     */
    function asSql($query)
    {
        return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(static function ($binding) {
            $binding = addslashes($binding);
            return is_numeric($binding) ? $binding : "'{$binding}'";
        })->toArray());
    }
}

2) In app/Providers/AppServiceProvider.php add this to register that new helper method:

/**
 * Register services.
 *
 * @return void
 */
public function register()
{
    // require all files in app/Helpers/ so their functions get added globally 
    foreach (glob(app_path('Helpers') . '/*.php') as $file) {
        require_once $file;
    }
}

3) With phpstorm (or similar IDE) set a breakpoint in vendor/backpack/crud/src/app/Library/CrudPanel/Traits/Read.php->getEntries()

set your breakpoint on this line $entries = $this->query->get();

If you're in php storm, load a list page and let the breakpoint hit, open the evaluator tool and run asSql($this->query) and you will see the fully bound query that will be run to get your records.

Like this:

enter image description here

This is the query for my user CRUD for which I've added the below in my setup:

$this->crud->addClause('where', 'active', 1);
$this->crud->orderBy('email');

NOTE, this probably wont show queries run to get the relationships for those models if applied, that gets a lot trickier in some cases.

If you are not running php storm with xdebug, or you just dont want to do it there, you could also add do this from your crud controller at the bottom of you setupListOperation method with something like

$sql = asSql($this->crud->query);
dd($sql);