Blog Image

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’)
->get();

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



Author: admin

Vinod Ram has been in Software Industry since 2006 and has experience of over 16 years in Software Development & Project Management domain specialised majorly in LAMP stack & Open Source Technology, building enterprise level Web based Application, Large Database driven and huge traffic Websites and Project Management. He loves to write information articles and blog to share his knowledge and experience with the outside world and help people to find solution for their problems.