How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

0 votes

Given the following code:

DB::table('users')->get();

I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users.

How do I do this?

Jul 21 in PHP by kartik
• 26,940 points
50 views

1 answer to this question.

0 votes

Hello @kartik,

Use the toSql() method on a QueryBuilder instance.

DB::table('users')->toSql() would return:

select * from `users`

This is easier than wiring up an event listener, and also lets you check what the query will actually look like at any point while you're building it.

Thank you!!

answered Jul 21 by Niroj
• 58,100 points

Related Questions In PHP

0 votes
2 answers
0 votes
1 answer

How can I convert the output of PHP's filesize() function to a format with MegaBytes, KiloBytes etc?

Hello @kartik, Here is a sample: <?php // Snippet from ...READ MORE

answered Sep 15 in PHP by Niroj
• 58,100 points
37 views
0 votes
1 answer

How can I capture the result of var_dump to a string?

Hello @kartik, Try var_export You may want to check out var_export — ...READ MORE

answered Sep 16 in PHP by Niroj
• 58,100 points
11 views
0 votes
1 answer

How to pass an array within a query string?

Hello, Submitting multi-value form fields, i.e. submitting arrays ...READ MORE

answered Apr 7 in PHP by Niroj
• 58,100 points
1,438 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 58,100 points
2,144 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 58,100 points
233 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 58,100 points
187 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 58,100 points
2,627 views
0 votes
1 answer

How do I get a YouTube video thumbnail from the YouTube API?

Hello @kartik, Each YouTube video has four generated ...READ MORE

answered Jun 16 in PHP by Niroj
• 58,100 points
197 views
0 votes
1 answer

How do I recursively delete a directory and its entire contents files as well as sub dirs in PHP?

Hello @kartik, The user-contributed section in the manual ...READ MORE

answered Aug 24 in PHP by Niroj
• 58,100 points
35 views