Skip to content

Instantly share code, notes, and snippets.

@franzliedke
Created March 1, 2016 12:52
Show Gist options
  • Save franzliedke/e351e4a4d4f7d3d481a4 to your computer and use it in GitHub Desktop.
Save franzliedke/e351e4a4d4f7d3d481a4 to your computer and use it in GitHub Desktop.
Laravel scope with binding
<?php
class SomeModel extends Eloquent
{
public function scopeSomething(Builder $query, $something)
{
// This will properly set up a binding
return $query->where('something', $something);
}
public function scopeSomethingAndOr(Builder $query, $something, $connector)
{
if ($connector == 'and') {
return $query->where('something', $something);
} else {
return $query->orWhere('something', $something);
}
// Really, you can shorten this to the following:
// return $query->where('something', '=', $something, $connector)
}
}
@franzliedke
Copy link
Author

Hi there, I hope I understood you correctly and this isn't what you already knew anyhow.

You can use any query method in a scope method, as you receive the query that's being built as the first object. Using where, orWhere or similar methods will give you properly ordered bindings for free.

The second example shows you how to switch the binary sorting logic based on a parameter, if that's what you want.

I'll reply tomorrow, I need to go to bed. ;)

@SteveEdson
Copy link

I think my issue is that I need to use WHERE st_contains(bounds, POINT(:lat, :lng)

What I have is

                    ->whereRaw('search_type = :type AND st_contains(bounds, POINT(:lat, :lng))')
                    ->setBindings([
                        'type' => $type,
                        'lat' => $lat,
                        'lng' => $lng
                    ]);

However, when I combine it with another scope that uses SELECT st_distance(location, POINT(:latDistance, :lngDistance)) as distance I get an error for incorrect number of parameters. I assume this is because the scope wipes out the previous bindings.

If I use $query->getBindings() with an array merge, it returns a numerically indexed array, without the keys I previously set. This then makes PDO complain about mixed named and numeric parameters.

If I change all my queries to use ? instead of named parameters, Laravel sets them in the wrong order :/.

@SteveEdson
Copy link

Additionally, if I mix a scope like the one above with another one as simple as return $query->where('search_type', 'proximity');, the mixed named and positional parameters error returns.

@franzliedke
Copy link
Author

Hmm, whereRaw accepts a second parameter called bindings: https://github.com/laravel/framework/blob/c858d541b1a05c3a13734c17f5d9e69fe6e1502b/src/Illuminate/Database/Query/Builder.php#L564

You should try that (with numeric indices and question marks as placeholders, yes).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment