Laravel 10 Find Nearest Location By Latitude and Longitude Tutorial

Mar 27, 2023 . Admin

Hi dev,

Today our leading topic is laravel 10 find nearest location by lat and long. We will use find closest location with longitude and latitude laravel 10. we will help you to give an example of how to find near location using latitude and longitude in laravel 10. We will look at an example of laravel 10 find near by lat and long. follow the below step for get nearest location based on latitude and longitude laravel 10.

You may quickly locate nearby destinations if you know their latitude and longitude coordinates, including businesses, residences, hotels, cities, states, and countries, as well as their products, dealers, and suppliers. I'll use a straightforward example. In order to locate users by the closest latitude and longitude, we will add lat and long to the users table.

Let's follow the below step to do this example.

Step 1: Install Laravel

first of all we need to get fresh Laravel version application using bellow command, So open your terminal OR command prompt and run bellow command:

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

In this is step we need to create one route for getting 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

in this step, we need to create LocationController and add following code on that file. you have users table with lat and long columns. also 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(""
                        ,DB::raw("6371 * acos(cos(radians(" . $lat . ")) 
                        * cos(radians( 
                        * cos(radians(users.lon) - radians(" . $lon . ")) 
                        + sin(radians(" .$lat. ")) 
                        * sin(radians( AS distance"))
Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve	

Now, Go to your web browser, type the given URL and view the app output:


i hope it can help you...

#Laravel 10