Last active
May 17, 2019 13:45
-
-
Save di3/8d21d540e3b8b6265cff69c3fb0d05bd to your computer and use it in GitHub Desktop.
laravel city model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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