Tags
Asked 2 years ago
17 Jun 2021
Views 150
Esteban

Esteban posted

print query in laravel

print query in laravel
ravi

ravi
answered Apr 27 '23 00:00

You can print the last executed SQL query in Laravel using the toSql() method. Here's how to do it:

First, build your query using the Laravel Query Builder:



$users = DB::table('users')
            ->where('name', 'John')
            ->get();

This query selects all users with the name "John" from the users table.

Next, call the toSql () method on the query builder instance to get the raw SQL query:



$query = $users->toSql();

The $query variable now contains the raw SQL query that was executed for the query.

Finally, you can print the query using the dd() function:



dd($query);

This will print the query and exit the script.

Alternatively, you can use Laravel's built-in query logging to print all executed queries to the log file. Here's how to do it:

Enable the query log by setting the DB_LOG_QUERIES environment variable to true in your .env file:



DB_LOG_QUERIES=true

Build your query using the Laravel Query Builder as usual:



$users = DB::table('users')
            ->where('name', 'John')
            ->get();

This query selects all users with the name "John" from the users table.

The query log will now contain the last executed query. You can view the log file to see the query. By default, the log file is located at storage/ logs /laravel.log.

Note that if you want to print the query to the screen instead of logging it, you can use the Log::info() function:


Log::info(DB::getQueryLog());

This will print the query log to the log file and exit the script.
Post Answer