Home Laravel Laravel 9 Find Nearest Location By Latitude And Longitude

Laravel 9 Find Nearest Location By Latitude And Longitude

by Shahriar Sagor

Hello Dev, Today now in this tutorial i will show you an example of laravel 9 find nearest location by lat and long. Here i will help you to give example of find closest location also with longitude and latitude laravel 9. if you want to see example of how to find the near location by using latitude and longitude in laravel 9 then i hope you are a right place. From here you’ll learn laravel 9 find near by lat and long.

Let’s start and follow the below step to do this example.

Step 1: Install Laravel

At first of all we have to get the fresh Laravel version application by using the bellow command. So open your terminal OR command prompt and then run the bellow command:

composer create-project laravel/laravel blog
Step 2: Create Route

Now in this is step i have to create one route for getting the near location from lat and long example.


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LocationController;
| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
Route::get('near-by-places', [LocationController::class, 'index']);
Step 3: Create Controller

Then now in this step, i have to create the LocationController and then add following code on that file. i have users table with lat and long columns. also i add some dummy records on table as well.


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Model\User;
class LocationController extends Controller
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
    public function index(Request $request)
        $users = User::select("users.id"
                        ,DB::raw("6371 * acos(cos(radians(" . $lat . ")) 
                        * cos(radians(users.lat)) 
                        * cos(radians(users.lon) - radians(" . $lon . ")) 
                        + sin(radians(" .$lat. ")) 
                        * sin(radians(users.lat))) AS distance"))

Read Also: Laravel 9 Restrict User Access From IP Address

Thanks for read. I hope it help you. For more you can follow us on facebook


You may also like