x-yuri x-yuri - 4 months ago 11
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?


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();