Laravel Pagination with haversine formula in it I'm using the haversine formula to count distance from selected post-code to desired destination.

I have the following scope in App\Models\Business.php:

public function scopeDistance($query, $latitude, $longitude, $radius)
{
    $query-&gt;getQuery()-&gt;orders = [];
    return $query-&gt;select('*')
                 -&gt;selectRaw("( 3959 * acos( cos( radians($latitude) ) * cos( radians( latitude ) )  * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin(radians(latitude)) ) ) AS distance")
                 -&gt;having('distance', '&lt;=', $radius)
                 -&gt;orderBy('distance');
}


Everything seems pretty ok, except the case when I use the paginate() method instead of get() in builder.

There are solutions out there, but I couldn't get these to work or were too complicated. I came up with this solution and I would like to hear feedback in terms of performance or memory usage.

This is the query at the end:

"select count(*) as count from (select ( 3959 * acos( cos( radians(51.5872718) ) * cos( radians( latitude ) )  * cos( radians( longitude ) - radians(-0.549759) ) + sin( radians(51.5872718) ) * sin(radians(latitude)) ) ) AS distance from `businesses` having `distance` &lt;= ?) as harversine"


and custom_pagination function:

function custom_paginator($builder, $per_page)
{
    $path = current_route();
    $current_page = \Illuminate\Pagination\Paginator::resolveCurrentPage();

    if ( ! isset($builder-&gt;getQuery()-&gt;columns[1])) $count = $builder-&gt;count();
    else
    {
        $query = clone $builder-&gt;getQuery();
        $query-&gt;columns = [ $query-&gt;columns[1] ];
        $query-&gt;orders = null;
        $count = array_get(\DB::select("select count(*) as count from ({$query-&gt;toSql()}) as haversine", $query-&gt;getBindings()), 0)-&gt;count;
    }

    return new \Illuminate\Pagination\LengthAwarePaginator(
        $builder-&gt;forPage($current_page, $per_page)-&gt;get(),
        $count, $per_page, null, compact('path')
    );
}


Is there anything I should change or improve?
I think that working with a natural language style query builder has sent your implementation a little astray. I don't understand why you need to select a count of rows from a sub-queried result set when you could just count the rows returned from the query itself, without even pulling the result set down into the application.

Outside of that, I find your code hard to read.


Don't mix use of brackets on each side of if-else conditional
Consider using PSR-2 compliant styles


putting start of brackets for functions/methods, conditionals and looping constructs on same line. 
Don't mix snake_case and camelCase within your user-written code.
One instruction per line.

Limit line lengths to ~80 characters.