Show your query with values in Laravel 10 Eloquent
When debugging your eloquent model queries, it’s often nice to know which SQL query is executed in the end.
By default, Laravel won’t show you the values used in the query. Instead, it shows you a questionmark ?
instead of the actual values. This is because of the parameter bindings in PDO.
Let’s create a ->toSqlWithBindings()
macro so you can have the full query.
Create the macro as ServiceProvider
<?php
// file app/Providers/MacroServiceProvder.php
declare(strict_types=1);
namespace App\Providers;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class MacroServiceProvider extends ServiceProvider
{
public function boot(): void
{
Builder::macro('toSqlWithBindings', function () {
/** @var Builder $this */
$bindings = array_map(
fn ($parameter) => (is_string($parameter) || $parameter instanceof Carbon) ? "'{$parameter}'" : $parameter,
/** @var Builder $this */
$this->getBindings()
);
return Str::replaceArray(
'?',
$bindings,
$this->toSql()
);
});
/** @var Builder $this */
EloquentBuilder::macro('toSqlWithBindings', fn () => $this->toBase()->toSqlWithBindings());
}
}