Home > database >  How to get the raw query and the list of columns from an Eloquent query
How to get the raw query and the list of columns from an Eloquent query

Time:05-29

Is it possible in Laravel, using eloquent to get the raw SQL query generated by the ORM query ?

Also, is it possible to get an array of all the columns involved in that query ?

Consider for exemple that Eloquent query:

$query = Category::join('posts', 'post.category_id', '=', 'category.id');

Would it be possible to retrieve in the code, the raw SQL of that query, and most importantly, an array of the columns involved ? In this cas, the columns of the Category and the Post models (category.id, category.name, post.id, post.title, post.category_id, etc...)

CodePudding user response:

You can enable ORM logging with:

DB::enableQueryLog();
// query

and when your query executed you can get it with:

DB::getQueryLog();

CodePudding user response:

You can use toSql() and getBindings() and for query builder same as:

$sql = $query->toSql();

$bindings = $query->getBindings();

If you do not provide any fields it will default to *

  • Related