ItSolutionStuff.com

Laravel Calculate Distance Between Two Latitude and Longitude Example

By Hardik Savani • April 16, 2024
Laravel MySql

Hey,

This example is focused on how to calculate distance between two latitude and longitude in laravel. In this article, we will implement a laravel calculate distance between two coordinates. I would like to show you calculate distance between two points in laravel. I’m going to show you about calculate distance between two coordinates laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Whenever you need to get nearest posts from lat and long and if you are working on laravel query builder. then you can get distance easily using DB::raw(), so you can learn from following example how to get nearest value from mysql laravel.

Example 1:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class ProductController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$lat = 51.0258751;

$lon = 4.4775352;

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"))

->groupBy("users.id")

->get();

dd("Users get successfully.");

}

}

I hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

šŸ“ŗ Subscribe on YouTube

We Are Recommending You

ā˜…

How to Search First Name and Last Name in Laravel Query?

Read Now →
ā˜…

Laravel Group By with Max Value Query Example

Read Now →
ā˜…

Laravel Eloquent orWhereHas() Condition Example

Read Now →
ā˜…

Laravel Search Case Insensitive Query Example

Read Now →
ā˜…

Laravel Eloquent When Condition Example

Read Now →
ā˜…

PHP Laravel Inner Join Query Example

Read Now →
ā˜…

Laravel Eloquent whereNotBetween() Query Example

Read Now →
ā˜…

Laravel Eloquent selectRaw() Query Example

Read Now →
ā˜…

Laravel Has Many Through Eloquent Relationship Tutorial

Read Now →
ā˜…

How to Search Comma Separated Values In Laravel?

Read Now →
ā˜…

Laravel Query Builder Where Exists Example

Read Now →
ā˜…

Example of unionAll in Query Builder Laravel

Read Now →
ā˜…

Laravel Join with Subquery in Query Builder Example

Read Now →