Skip to content

Instantly share code, notes, and snippets.

@di3
Last active May 17, 2019 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save di3/8d21d540e3b8b6265cff69c3fb0d05bd to your computer and use it in GitHub Desktop.
Save di3/8d21d540e3b8b6265cff69c3fb0d05bd to your computer and use it in GitHub Desktop.
laravel city model
<?php
namespace App\Models;
class City extends Model {
/**
* The database table used by the model.
* @var string
*/
protected $table = 'cities';
public $timestamps = false;
protected $fillable = [
'state_id',
'county_id',
'name',
'lat',
'lng'
];
protected $hidden = [
'state',
'county',
'language'
];
/**
* return nearest cities and includes the distance
* @param unknown $query
* @param unknown $lat
* @param unknown $lng
*/
public function scopeNearest($query, $lat, $lng) {
$db = app('db')->connection();
$query->select($db->raw(
'*, 111.045 * DEGREES(ACOS(COS(RADIANS('.$lat.'))' .
' * COS(RADIANS(lat))' .
' * COS(RADIANS(lng) - RADIANS('.$lng.'))' .
' + SIN(RADIANS('.$lat.'))' .
' * SIN(RADIANS(lat)))) AS distance'
))
->orderBy('distance','ASC');
}
public function zipcodes() {
return $this->hasMany('App\Models\Zipcode');
}
public function state() {
return $this->belongsTo('App\Models\State');
}
public function county() {
return $this->belongsTo('App\Models\County');
}
public function language() {
return $this->belongsTo('App\Models\Language');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment