Tags
Asked 2 years ago
17 Jun 2021
Views 162
Allene

Allene posted

How to get raw sql that is being executed in Laravel 5 ?

How to get raw sql that is being executed in Laravel 5 ?
angeo

angeo
answered Apr 27 '23 00:00

In Laravel 5, you can get the raw SQL that is being executed using the toSql () method. Here's how to do it:

First, you need to build your query using the Query Builder. For example, if you want to get the raw SQL for a SELECT query, you can do it like this:



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

In this example, we're querying the users table and getting all the users with the name "John".

Next, you can call the toSql () method on the query object to get the raw SQL:


$sql = $users->toSql();
echo $sql;

This code retrieves the raw SQL that is being executed for the query.

Note that if you're using Eloquent models, you can also get the raw SQL for a query by calling the toSql () method on the query builder returned by the model. For example:



$user = User::where('name', 'John')->get();
$sql = $user->toSql();
echo $sql; 

This will give you the raw SQL for the query that is being executed by the get() method on the User model.
Post Answer