x-yuri x-yuri - 3 months ago 8
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();


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

Answer

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]);
    }
}

Usage:

$latitude = 0.0;
$longitude = 180.0;
MyModel::sqlDistanceTo($latitude, $longitude)->get();