Skip to content

Instantly share code, notes, and snippets.

@di3
Last active May 17, 2019
Embed
What would you like to do?
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