Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Corbin's avatar

Trying to get property of non-object. Harvasine query scope.

I'm essentially trying to find the users closest to me with the harvastine algorithm.

ProfilesController

    public function index(User $user, Request $request)
    {
        //$location = GeoIP::getLocation($request->ip());
        $authUser = Auth::user();
        $users = $user->scopeIsWithinMaxDistance($authUser, 5 )->all();

        return view('profiles.index', compact('users'));

    }

User Model

public function scopeIsWithinMaxDistance($query, $location, $radius = 25) 
{

     $haversine = "(6371 * acos(cos(radians($location->lat)) 
                     * cos(radians(user.lat)) 
                     * cos(radians(user.lng) 
                     - radians($location->lng)) 
                     + sin(radians($location->lat)) 
                     * sin(radians(user.lat))))";
     return $query
        ->select() //pick the columns you want here.
        ->selectRaw("{$haversine} AS distance")
        ->whereRaw("{$haversine} < ?", [$radius]);
}

Error

ErrorException in User.php line 40: Trying to get property of non-object

0 likes
1 reply
Corbin's avatar
Corbin
OP
Best Answer
Level 9

Got it:

Profiles Controller

public function index(User $user, Request $request)
    {
        //$location = GeoIP::getLocation($request->ip());
        $authUser = Auth::user();


        $users = $user->scopeIsWithinMaxDistance($authUser->lat, $authUser->lng, 5 )->all();//paginate(20);

        view('profiles.index', compact('users'));

    }

User Model

public function scopeIsWithinMaxDistance($query, $lat, $lng,  $radius = 25) {

     $haversine = "(6371 * acos(cos(radians($lat)) 
                     * cos(radians(user.lat)) 
                     * cos(radians(user.lng) 
                     - radians($lng)) 
                     + sin(radians($lat)) 
                     * sin(radians(user.lat))))";
     return $query
        ->select('id') //pick the columns you want here.
        ->selectRaw("{$haversine} AS distance")
        ->whereRaw("{$haversine} < ?", [$radius]); 
    }

I now have the joy of getting a totally separate error. Which probably deserves its own thread because I can't find it anywhere with a google search.

Please or to participate in this conversation.