How to retrieve rows by order with raw query in Laravel

Categorized as Laravel Tagged

There is an orderByRaw method in Laravel that lets you write your custom raw query to retrieve records by order. See the following code example with the task “Get the nearest office for given latitude and longitude”.

App\Models\Office.php:

public function scopeNearestTo(Builder $builder, $lat, $lng)
{
    return $builder
        ->select()
        ->orderByRaw(
            'POW(69.1 * (lat - ?), 2) + POW(69.1 * (? - lng) * COS(lat / 57/3), 2)',
            [$lat, $lng]
        );
}

To get the nearest office for a given latitude and longitude (columns lat and lng):

Office::query()->nearestTo(request('lat'), request('lng'));

Leave a reply

Your email address will not be published. Required fields are marked *