Support the ongoing development of Laravel.io →
Database Eloquent

I have 2 tables:

User [ id, name, address_id, active ]

Address [ line1, line2, city, county, postcode, latitude, longitude ]

Now, I can select the address in order of distance using:

$addresses = Address::all()->addSelect(DB::raw("( 6371 * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance")) ->having("distance", "<", Input::get('distance')) ->orderBy('distance');

This works fine and selects the addresses in order of nearest to furthest.

I now need to select the Users in order of distance which I'm doing the following:

$users = User::active()->with('address') ->addSelect(DB::raw("( 6371 * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance")) ->having("distance", "<", Input::get('distance')) ->orderBy('distance');

Which also works, however when using the paginator this will fail with a syntax error.

$users = $users->paginate(20);

How can I make this select the users in order of distance? I'm completely stumped on how to solve this.

Thanks in advance.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

digitaldog digitaldog Joined 29 May 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.