How To Convert Laravel Query To SQL Query

Websolutionstuff | Oct-27-2022 | Categories : Laravel MySQL

In this article, we will see how to convert a laravel query to an SQL query. Many times we required laravel query builder to its raw SQL query as a string. Laravel provides different ways to get raw SQL queries. You can get SQL queries using the toSql() query builder method. Also, you can use the laravel query log to get SQL queries in laravel. For getting the query logs we will use enableQueryLog() method.

 So, let's see how to get the raw SQL query from a laravel.

The toSql() Function:

In this example, we will use the toSql() method to get raw SQL queries. toSql() get the SQL representation of the query and return the string value. This method doesn't show the whole query if your query is more complex or if there are sub-queries.

SQL Query Example:

SELECT * FROM articles WHERE status='published';

Laravel Query Example:

$articles = Article::where('status', 'published')->get();

Use the toSql() method, you can just change the get() part in the above query with toSql().

$article = Article::where('status', 'published')->toSql();

Output:

"select * from `articles` where `status` = ?"

 

 

The enableQueryLog() Function:

Laravel can optionally log into the memory of all queries that have been run for the current request. You can enable the log using the enableQueryLog() method.

public function store(Request $request){
    \DB::enableQueryLog();

    Post::where('is_active', '=', '1')        
    ->orderBy('publish_date', 'desc')
    ->limit(15)
    ->get();

    dd(\DB::getQueryLog());
}

Output:

array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `posts` where `is_active` = ? order by `publish_date` desc limit 15"
    "bindings" => array:1 [▶]
    "time" => 7.03
  ]
]

So, you can get out in array format with the query and execution time of the query.

\DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

dd(\DB::getQueryLog()); // Show results of log

 


You might also like:

Recommended Post
Featured Post
Laravel 8 One To Many Polymorphic Relationship
Laravel 8 One To Many Polymorp...

In this tutorial we will learn about laravel 8 one to many polymorphic relationship. A one-to-many polymorphic rela...

Read More

Nov-19-2021

Laravel 8 Eloquent whereHas Condition
Laravel 8 Eloquent whereHas Co...

In this example we will see laravel 8 eloquent whereHas() condition. you will learn about wherehas() condition in l...

Read More

Oct-06-2021

How To Install Bootstrap In React JS
How To Install Bootstrap In Re...

In this article, we will see how to install bootstrap in react js. Also, we will see how to use bootstrap in react...

Read More

Sep-08-2022

How To Count Days Excluding Weekends And Holidays In Laravel 9
How To Count Days Excluding We...

In this article, we will see how to count days excluding weekends and holidays in laravel 9. Here, we will learn to...

Read More

Jan-24-2023