I want to get basketball courts on basis of given lat long in eloquent ORM. I tried to get that but here I got this error.
Call to undefined function App\Http\Controllers\Api\RADIANS()
is there any way to get nearby location using Eloquent if yes then how? please help me out I'm sharing me doings so far.
HomeCourt Controller
public function fetchHomeCourts(Request $request) {
$validator = Validator::make(
array(
'lat' => $request->lat,
'long' => $request->long,
),
array(
'lat' => 'required',
'long' => 'required',
)
);
if ($validator->fails()) {
$this->setMeta("422", Constant::MSG_422);
return response()->json($this->setResponse());
}
$homeCourt= HomeCourt::where(ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10)->first();
if(!$homeCourt) {
$this->setMeta("200", "No courts found");
$this->setData("homeCourts",$homeCourt);
return response()->json($this->setResponse());
}
$this->setMeta("200", "Home court list");
$this->setData("homeCourts",$homeCourt);
return response()->json($this->setResponse());
}
So this is what basically happens:
The user will give you the coordinates they are interested in (via a magic procedure, most pages supply a map that the users click on but it's really what is best for your users).
This is what your code needs to read:
public function fetchHomeCourts(Request $request) {
$validator = Validator::make(
array(
'lat' => $request->lat,
'long' => $request->long,
),
array(
'lat' => 'required',
'long' => 'required',
)
);
if ($validator->fails()) {
$this->setMeta("422", Constant::MSG_422);
return response()->json($this->setResponse());
}
$homeCourt= HomeCourt::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10")->first();
if(!$homeCourt) {
$this->setMeta("200", "No courts found");
$this->setData("homeCourts",$homeCourt);
return response()->json($this->setResponse());
}
$this->setMeta("200", "Home court list");
$this->setData("homeCourts",$homeCourt);
return response()->json($this->setResponse());
}
The whereRaw
bit will pass that whole formula to MySQL directly instead of having Laravel trying to figure out how to build it into a query (since it's not a standard format that Laravel can handle.
From what I understand that formula is basically the for the distance on a the curved surface of the earth ( 6380 is the radius of earth in km and the rest looks like he arc-distance of two points).
Assuming that all courts you are interested in are stored in your database (you can either have a manual list or update them using some sort of overnight process to get it from somewhere) you don't need to run an API query on every request.