Home > Software engineering >  How to get the raw SQL query from the Laravel Query Builder in laravel8.0
How to get the raw SQL query from the Laravel Query Builder in laravel8.0

Time:01-19

Using Laravel Eloquent methods The first method to get the query of an Eloquent call is by using the toSql() method. This method returns the query without running it – good if you don't want to alter data and only get the query – but this method doesn't show the whole query if your query is more complex or if there are sub-queries.

enter code here

App\User::query()
    ->where('created_at', '<', now()->subYear())
    ->with('assignedApps', 'courses')
    ->orderBy('email', 'asc')
    ->limit(5)
    ->toSql();

CodePudding user response:

If you want to show all the queries, then you will have to enable the query log. DB::enableQueryLog

\DB::enableQueryLog(); // enable the query log before your modal

App\User::query()
    ->where('created_at', '<', now()->subYear())
    ->with('assignedApps', 'courses')
    ->orderBy('email', 'asc')
    ->limit(5)
    ->get();

dd(DB::getQueryLog()); // after your query, dump and die get query log. 

It will return all queries result with values

  •  Tags:  
  • Related