Most often laravel dev prefer to log the sql query by using below snippet.
DB::listen(function ($query) {
info('Query', [
"Query" => $query->sql,
"Bindings" => $query->bindings,
"Time" => $query->time,
]);
});
But the drawback of this is it split out the query, sql bindings and it's time.
we can do it in a better way to combine the query and it's bindings by using laravel
Macroable Trait.
Add the Below snippet in AppServiceProvider
and you are good to go.
Builder::macro('toSqlWithBindings', function () {
$bindings = array_map(fn($value) =>
is_numeric($value) ? $value : "'{$value}'",
$this->getBindings()
);
return Str::replaceArray(
'?', $bindings, $this->toSql()
);
});
Most of the laravel illuminate classes are by default uses Macroable Trait. By Using that we can add our custom function to that illuminate classes. These functions are available as class function. so we can here chain the custom function to query builder.
$query = User::where('name', 'like' , '%admin%');
$query->toSqlWithBindings();
Output
select * from `users` where `name` like '%admin%' and `users`.`deleted_at` is null`
Keep Learning!!
Top comments (0)