Reputation: 80
I'm curious about how can I convert this query to Laravel query.
here is my nearby query I tried on phpmyadmin exactly working.
set @lat=37.034126;
set @lng=27.430235;
SELECT party_title, latitude, longitude, 111.045 * DEGREES(ACOS(COS(RADIANS(@lat))
* COS(RADIANS(latitude))
* COS(RADIANS(longitude) - RADIANS(@lng))
+ SIN(RADIANS(@lat))
* SIN(RADIANS(latitude))))
AS distance_in_km
FROM parties
ORDER BY distance_in_km ASC
LIMIT 0,5
query result :
I tried like this but it didnt work.
public function index(\Illuminate\Http\Request $request) {
if($request->has('party_category')){
$parties = Parties::where('party_category', $request->party_category)->get();//your new query here
}
else if($request->has('lat') && $request->has('long')){
$parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))")->get();
}else {
$parties = Parties::all();
}
return Fractal::includes('places')->collection($parties,new PartyTransformer);
}
I'm curious how can I convert query and how can I get distance_in_km value from query becuase I want to show in api response.
Upvotes: 0
Views: 139
Reputation: 80
I fixed problem , here is code I hope it will help somebody :
class PartiesController extends Controller
{
public function index(\Illuminate\Http\Request $request) {
if($request->has('lat') && $request->has('long')){
$lat = $request->lat;
$long = $request->long;
$parties=DB::select(DB::raw("SELECT *,111.045*DEGREES(ACOS(COS(RADIANS(':lat'))*COS(RADIANS(`latitude`))*COS(RADIANS(`longitude`) - RADIANS(':long'))+SIN(RADIANS(':lat'))*SIN(RADIANS(`latitude`)))) AS distance_in_km FROM parties ORDER BY distance_in_km asc LIMIT 0,5"), array(
'lat' => $lat,
'long' => $long
));
$hidacik = Parties::hydrate($parties);
return Fractal::includes('places')->collection($hidacik,new PartyTransformer);
}
else {
$parties = Parties::all();
}
return Fractal::includes('places')->collection($parties,new PartyTransformer);
}
}
Upvotes: 1
Reputation: 46
Replace whereRaw with selectRaw as you are applying select statement on the raw query.
Upvotes: 0