In Laravel sometimes we need to get the executed query log, first executed query or the last executed query. Sometimes, you need to debug or display SQL query via laravel query builder. Here in this tutorial, i am going to enumerate few debugging demos with examples for executed queries in Laravel 7.

When you build a web application, so its highly possible, you need to print or debug last run query. However, this can be directly done in PHPMyAdmin SQL tab.

This is why in this tutorial. We are explaining how to debug SQL query from the MySQL Database query builder.

Last Query in Laravel Eloquent

It is straightforward to get the current SQL query you can do it with Laravel query builder’s toSql() method. To propel the development performance, we don’t need to enable the query log, just execute the query as shown below.

$product = Product::where('id',77)->toSql();
dd($product);

PHPCopy

Last Query in Laravel Eloquent

Now, let’s enable the query log by taking the help of Laravel query builder’s  DB::enableQueryLog() method. The enableQueryLog() method stores all the executed queries in the cache that we can easily access with  DB::getQueryLog()method.

You will notice that in this example, we are not focusing on laravel the last query, instead giving attention to getting all the query log.

DB::enableQueryLog();
$product = Product::get();
$query = DB::getQueryLog();
dd($query);

#laravel #laravel 7

Simple way to Print or Get Last Executed Query in Laravel 7
25.80 GEEK