0

I am using laravel 7.7.1 and in a query I pass a variable iaw the docs like so:

public function show($graad=3)
    {
        $sums=Sum::where(function ($query) use($graad) { 
            $query->where('graad',$graad);
            })->inRandomOrder()->limit(1)->toSql();

Result is always:

"select * from `sums` where (`graad` = ?) order by RAND() limit 1"   

So the variable is not passed in the correct way and converted to a "?".

Changing the value of $graad='test' or $graad='3' or even typehinting with

 public function show(int $graad=3)

does result in

 "select * from `sums` where (`graad` = ?) order by RAND() limit 1"

The column graad in the table is an int(11). What am I doing wrong?

Erikkie
  • 1
  • 1
  • It is a security feature to prevent __sql injecttions__ – Tharaka Dilshan May 06 '20 at 05:38
  • Neither you nor the ORM are doing anything wrong. What you see is the expected result of the `toSql()` function. Please read all of [this](https://phptherightway.com/) before picking up a framework. – kalatabe May 06 '20 at 05:50
  • This is returning query instance. When you will pass the parameters, it will replace them in the place of ```?``` and execute on ```->get()``` function call. – S K R May 06 '20 at 06:24

3 Answers3

0

I think you are missing the get()

try:

$sums = Sum::where('graad', $graad)->inRandomOrder()->limit(1)->get();

or

$sums = JOBS::where(function($query) use ($graad){        
    $query->where('graad', $graad);
})->inRandomOrder()->limit(1)->get();
public function show($graad)
{
   // Rest of your code

And then make sure your route is receiving the value in the url and sending along (Assuming this is how you are calling the method).

Route::get('your-route-name/{graad}', 'YourController@show');
jeremykenedy
  • 4,150
  • 1
  • 17
  • 25
0

Laravel under the hood uses Prepared Statements. This is to avoid SQL injection. The ? is the placeholder for the data that will be substituted later by the bindings.

You can use $query->getBindings(); to fetch the data that will be binded in SQL statement.

sn n
  • 319
  • 1
  • 5
  • 19
-1

Please try this below:

public function show($graad=3)
    {
        $sums=Sum::where(function ($query) use($graad) { 
            $query->where('graad',$graad);
            })->inRandomOrder()->limit(1);
        vsprintf(str_replace(['?'], ['\'%s\''], $sums->toSql()), $sums->getBindings());
tesmojones
  • 2,496
  • 2
  • 21
  • 40
  • Please don't teach people to perform SQL injections on themselves. – kalatabe May 06 '20 at 05:50
  • character "?" is placeholder for binding value of $graad, it is normal output and can not be changed. for complete explanation or solution for debugging, please refer to https://stackoverflow.com/questions/32372437/does-laravels-tosql-method-mask-ids-column-value-being-replaced-by-question – tesmojones May 06 '20 at 06:02
  • the answer of tesmojones was for me the right answer. Thanks all! – Erikkie May 06 '20 at 07:14