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

shadrix's avatar
Level 12

How would you get the Eloquent Model? Using a Raw Database Query for GeoLocation

I've no clue how to transform this query to get an eloquent model.

 return DB::select('SELECT *, 
            ? * 2 * ASIN(SQRT(POWER(SIN((? - abs(dest.lat)) * pi()/180 / 2),2)
            + COS(? * pi()/180 ) * COS(abs(dest.lat) * pi()/180) * POWER(SIN((? - dest.lng) * pi()/180 / 2), 2) ))
            as distance
            FROM sell_maps dest
            having distance < ?
            ORDER BY distance limit 10', [$R, $userlocation['lat'], $userlocation['lat'], $userlocation['lng'], $distance]);

I would love to use a static search like: $sellitems = App\SellMap::nearYou(variables);

so that I can lazy load it later.

0 likes
2 replies
shadrix's avatar
shadrix
OP
Best Answer
Level 12

Okay that was easy. Sorry for the question:

 public static function nearyou($R, $userlocation, $distance){
    return static::select('*')
                    ->selectRaw('? * 2 * ASIN(SQRT(POWER(SIN((? - abs(dest.lat)) * pi()/180 / 2),2)
                        + COS(? * pi()/180 ) * COS(abs(dest.lat) * pi()/180) * POWER(SIN((? - dest.lng) * pi()/180 / 2), 2) ))
                        as distance', [$R, $userlocation['lat'], $userlocation['lat'], $userlocation['lng']])
                    ->from('sell_maps as dest')
                    ->havingRaw('distance < ?', [$distance])
                    ->orderBy('distance')
                    ->take(10)
                    ->get();
}
d3mo's avatar

hi shadrix i want to ask you a question what is this R variable because i am using your query in my project

Please or to participate in this conversation.