1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| <?php
namespace App\Http\Controllers;
use App\Models\School; use Illuminate\Support\Facades\Validator; use Illuminate\Http\Request;
class SearchController extends Controller { public function index(Request $request) { $input = $request->only(['lat', 'lng']);
$validator = Validator::make($input, [ 'lat' => [ 'required', 'regex:/^[\-\+]?(0?\d{1,2}\.\d{1,6}|1[0-7]?\d{1}\.\d{1,6}|180\.0{1,6})$/' ], 'lng' => [ 'required', 'regex:/^[\-\+]?([0-8]?\d{1}\.\d{1,6}|90\.0{1,6})$/' ], ]);
if($validator->fails()) { return $validator->errors()->first(); }
$distance = $request->query('distance', 5);
$data = School::select('*') ->selectRaw('( 6371 * acos( cos( radians(' . $input['lat'] . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $input['lng'] . ') ) + sin( radians(' . $input['lat'] .') ) * sin( radians(lat) ) ) ) AS distance') ->havingRaw('distance < ' . $distance) ->orderBy('distance') ->get();
return response()->json([ 'data' => $data, ]); } }
|