skip to Main Content

I’m on Laravel 10, and new to it too. I did a simple query like this

Sample::where(
                [
                    ['query_string', '=' , $string], 
                    ['from', '=', 'usa'],
                    ['status_id', '=', '1'],
                    ['created_at', '>', 'NOW() - INTERVAL 7 DAY']
                ]
            )->toSql();

which generates a query like this

"select * from `sample` where (`query_string` = ? and `from` = ? and `status_id` = ? and `created_at` > ?)"

how come the variable values don’t show, it only shows a question mark? which causes the query to return null when i change ->toSql() to ->first()

How do I get it to return the results of the query when i change it to ->first()?

2

Answers


  1. You see the question marks in the SQL because it will be used in a prepared statement.

    The question marks are called "anonymous positional placeholders".

    A prepared statement is essential to prevent SQL-Injection.

    When you change ->toSql() to ->dd() you will see values instead of placeholder, but remember to never execute such a SQL string, because you’ll be then defeating the protection mechanism, against SQL-injection, of Eloquent.

    Login or Signup to reply.
  2. As long as your other where clause values don’t exclude any results the main reason your query is returning null because the created_at parameter is being interpreted as a string and not additional SQL.

    This part of your where clause

    ['created_at', '>', 'NOW() - INTERVAL 7 DAY']
                        ^^^^^^^^^^^^^^^^^^^^^^^^
    

    will produce the query

    select ... where ... AND created_at = "NOW() - INTERVAL 7 DAY"
    

    note: double quotes used to emphasise the problem

    either calculate the date in PHP and insert that as the parameter, or change the code to use DB::raw

    ['created_at', '>', DB::raw('NOW() - INTERVAL 7 DAY')]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search