I'm working in Laravel and I'm interested in checking the SQL statements generated by a Eloquent query that includes a with() statement. For some reason I'm getting only the main query. For example, when I run
class Child extends EloquentVersioned {
public function childRequests()
{
return $this->hasMany('ChildRequest');
}
}
$childQuery = Child::orderBy('last_name')->orderBy('first_name')->with( 'childRequests');
return $childQuery->toSql();
I get back:
select `children`.* from `children` order by `last_name` asc, `first_name` asc
How do I get back the SQL for the with('childRequests') query?
Actually, when using with
then Laravel
uses another query for that so you are not getting that query output but if you use DB::getQueryLog()
then you'll get all the query logs and to get your log you may run the actual query, for example:
Child::orderBy('last_name')->orderBy('first_name')->with( 'childRequests')->get();
Now try this:
dd(DB::getQueryLog()); // an array of all queries
You'll get an output of your queries and you may find the last query using:
$queries = DB::getQueryLog();
dd(end($queries)); // only last query
Troubleshooting
If you get no results on
DB::getQueryLog()
then the Query Logger may be disabled at all and you have to useDB::enableQueryLog()
before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With