Search code examples
mysqlsqllaraveleloquentlaravel-query-builder

laravel Eloquent/QueryBuilder - Why the value of variable $prod is become"?" in the Sql query?


Sorry for my English grammar,..

I want to execute this query but is getting 0 result,.. i try to check in ->toSql() function i saw the value become ?,. instead of the value is "pork",. why is become (?) question mark? and how to fix it?

this my laravel queries using model

$items = Item::where("item_type_id", "!=", 1)
            ->where(function ($query) use ($prod){
                    $query->where("description", "like", "'%$prod%'")
                    ->orWhere("id", "'%$prod%'");
            })
            ->toSql(); 
dd($items);

and the result is this, and the parameters become "?".

"select * from `items` where `item_type_id` != ? and (`description` like?or `id` =?)"


Solution

  • ? it's call Bindings used for SQL injection. if you want to get the bindings variable then you can use getBindings() method.

    Check more detail of getBindings()

    $items = Item::where("item_type_id", "!=", 1)
                ->where(function ($query) use ($prod){
                        $query->where("description", "like", "'%$prod%'")
                        ->orWhere("id", "'%$prod%'");
                });
    
    $sqlquery = $items->toSql(); 
    $bindings = $items->getBindings();
    

    Another way to replace ? to value is below.

    $sql_with_bindings = str_replace_array('?', $items->getBindings(), $items->toSql());
    

    One more way to check the last executed query is DB::enableQueryLog().

    \DB::enableQueryLog();
    $items = Item::where("item_type_id", "!=", 1)
                  ->where(function ($query) use ($prod){
                       $query->where("description", "like", "'%$prod%'")
                             ->orWhere("id", "'%$prod%'");
                    })->get();
    dd(\DB::getQueryLog());