x-yuri x-yuri - 1 year ago 52
PHP Question

How to use named bindings with laravel's query builder?

I'd like to do the following:

MyModel::where(MyModel::sql_distance_to(), ['lat' => '...', 'lng' => '...'])->get();

returns some complex sql expression. But from what I can see, query builder doesn't support named bindings. Is this true? Any workaround?

Answer Source

I belive you mean using Query Scopes

class MyModel extends Model
    public function scopeSqlDistanceTo($query, $lat, $lon)
        // Previously DB::raw(expr) was here.
        // No need since we're using whereRaw()
        $whereRaw = 'lat = ? AND lon = ?';

        return $query->whereRaw($whereRaw, [$lat, $lon]);


$latitude = 0.0;
$longitude = 180.0;
MyModel::sqlDistanceTo($latitude, $longitude)->get();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download