Search code examples
phpmysqllaravelexplain

How to execute an `explain select` on a laravel builder


I know I could get the raw query from the query log, paste in all the bound variables (also found in the query log), slap a explain at the front of the query, and run it directly in the mysql console to get the explanation for the query.... but is there any quicker way to get the explanation?

Ideally, I'd like to do something like this:

$query = User::where("favorite_color", "blue");

dd($query->explain());

(obviously, the actual query is going to be much more complicated and have some joins)

I tried adding on the explain like this:

$query->selectRaw("explain select user.*");

But this resulted in a query that started with:

select explain select...

... which is just invalid sql.


Solution

  • As of Laravel 8.12, you can simply call ->explain() on the query builder, like you described in your question. Or use ->explain()->dd() to die & dump the explanation.

    Example:

    User::where("favorite_color", "blue")->explain()->dd();