Using toSql Function to Print SQL Query in Laravel

Posted on

Somehow, in the development process of a web application based on Laravel PHP Framework, there is a further need to check and recheck the query which is used in the script. Especially if it is actually build with the help of library provided in Laravel PHP Framework. Using the help of ‘DB’ facade which is part of Laravel PHP Framework, it can be specifically modified to print the query which is being used or aim to be executed.

Below is an example of the usage using DB Facade in a controller file :

        
public function edit($id_server){
    $selected_server = DB::table('server as a')
    ->select('a.*', 'b.name as name', 'c.name as position')
    ->leftjoin('user as b','b.id_user','=','a.id_user')
    ->leftjoin('role as c','b.id_role','=','c.id_role')
        ->where('a.id_server','=',$id_server)
    ->toSql();
    return $selected_server;
}

The above is a snippet code extracted from a controller named ‘ServerController.php’ which is obviously has a main class of ‘ServerController’. In this file or within the class, there is a function named ‘edit’. This function is used to edit server but it will execute a query to a table named ‘server’ via a model named ‘Server.php’. The DB facade is used to specify a table and furthermore it is specifically a query to be executed. The query which is specified in the above snippet code will be stored in a variable named ‘$selected_server’.

To be able to display it, the following line of code ‘return $selected_server’ will redirect the output generated by the execution of the function toSql(). So, in this article,  the main focus of the above snippet code is the part ‘->toSql()’. It will convert totally as a full query which is already specified as the snippet code shown above.

The output of the above command execution is shown below :

select `a`.*, `b`.`nama` as `name`, `c`.`name` as `position` from `server` as `a` left join `user` as `b` on `b`.`id_user` = `a`.`id_user` left join `role` as `c` on `b`.`id_role` = `c`.`id_role` where `a`.`id_server` = ?
</>

The above function, toSql() will be quite an advantage for developer or programmer since the only output shown is simply the query without having to display another content which can cause unnecessary distraction. The image which is depicted the shown below :

Using toSql Function to Print SQL Query in Laravel
Using toSql Function to Print SQL Query in Laravel

One thought on “Using toSql Function to Print SQL Query in Laravel

Leave a Reply