Hello friend, if you have a big project to query database and want to know how does your query database is actually perform such in duration of manipulate as well as to whether your query statment is correct since Laravel using ORM which is manipulate data with PHP syntax. In this tutorial, we are going to learn how to get SQL statement in Laravel. Below example will help you handle in different way to print out SQL Query.
We will use toSql()
DB::enableQueryLog(), and DB::getQueryLog in Laravel 9 to show SQL query which perform by this PHP syntax. So let's take a look at below examples.
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$sql= User::get()->toSql();
dd($sql);
}
}
Output
select * from `users`
<?php
namespace App\Http\Controllers;
use App\Models\User;
use DB;
class UserController extends Controller
{
public function index()
{
// Enable log Query Statment;
DB::enableQueryLog();
$users = User::select("*")->get();
$quries = DB::getQueryLog();
dd($quries);
}
}
Output
array:1 [▼
0 => array:3 [▼
"query" => "select * from `users`"
"bindings" => []
"time" => 28.23
]
]
This examples give you idea how to get log or debug as the result in SQL query in your Laravel application. Hope this would help your project. Have a nice day!
You might also like...
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him