how to get sql query from facade DB::table in laravel 5

Normally we fetch the data as below

$dataresult = DB::table(‘sometable’)
->select(‘sometable.column1’, ‘sometable.column2’, ‘sometable.column3’, ‘sometable.column4’, ‘sometable.column5’)

Now if we want to get the actaul query from $dataresult using $dataresult->toSql(); // it will not work

The solution for this is first prepare the query without the get() method and then call the toSql() method as below.

$dataQuery = DB::table(‘sometable’)
->select(‘sometable.column1’, ‘sometable.column2’, ‘sometable.column3’, ‘sometable.column4’, ‘sometable.column5’);

$dataQuery->toSql(); // this will give you the actual query

After that you can fetch the result as below.
$dataresult = $dataQuery->get();

Read the next article to know how to get the sql with data binding

Leave your comment