Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ashewalton's avatar

Eloquent query ->toSql returning '?' for 3rd argument??

I'm new to Laravel, and I have created an eloquent query that's not working, so to troubleshoot I've output the SQL query.

$notepads = Notepad::where('id','1')->toSql
$notepads = Notepad::where('id','=','1')->toSql

In both instances it outputs the query select * from notepads where id = ? where I'm looking for a result of select * from notepads where id = 1

A similar instance of the same query WAS working, now it isn't. I'm just baffled as to why this seemingly simple query won't work.

0 likes
7 replies
jimmck's avatar

Eloquent is using 'Bind Parameters' in the PDO library. The ? is s placeholder for the data that will be supplied by the bind variable. What is the Full SQL error you are getting?

1 like
nvanselow's avatar

I ran across your question while searching for a similar thing. Hopefully this answer will help the next person.

You can get the value of the ? by calling getBindings.

$query = Notepad::where('id','1');
var_dump($query->toSql());
var_dump($query->getBindings());

will output

"select * from notepads where id = ?"

array(1) {
  [0]=>
    int(1)
}
3 likes
automica's avatar

@haroon-mahmood-4276 I know we're both answering a 4 year old question, but you may be interested in adding this method in your model which will allow you to access the query in a format you can run directly in mysql.

        /**
         * @param Builder $query
         * @return string
         */
        public static function getQueryWithBindings($query): string
        {
           return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
                $binding = addslashes($binding);
                return is_numeric($binding) ? $binding : "'{$binding}'";
            })->toArray());
        }

implement as such:

$query = Model::where('foo','bar');

$sql = Model::getQueryWithBindings($query);
5 likes

Please or to participate in this conversation.