Laravel Calculate Distance Between Two Latitude and Longitude Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Search First Name and Last Name in Laravel Query?
- Laravel Group By with Max Value Query Example
- Laravel Eloquent orWhereHas() Condition Example
- Laravel Search Case Insensitive Query Example
- Laravel Eloquent When Condition Example
- PHP Laravel Inner Join Query Example
- Laravel Eloquent whereNotBetween() Query Example
- Laravel Eloquent selectRaw() Query Example
- Laravel Has Many Through Eloquent Relationship Tutorial
- How to Search Comma Separated Values In Laravel?
- Laravel Query Builder Where Exists Example
- Example of unionAll in Query Builder Laravel
- Laravel Join with Subquery in Query Builder Example