Skip to content

Instantly share code, notes, and snippets.

@edfialk
Last active February 8, 2017 02:47
Show Gist options
  • Save edfialk/302d6f223fef76c0b34e60a620060b14 to your computer and use it in GitHub Desktop.
Save edfialk/302d6f223fef76c0b34e60a620060b14 to your computer and use it in GitHub Desktop.
In Laravel: when storing a new point, I didn't want it to be too close to another or have the same name in the same city. Proximity and distance use Haversine Formula.
<?php
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(PointCreateRequest $request)
{
$proximity = Point::centeredAt($request->lat, $request->lng, 0.0001);
if ($proximity->count() > 0){
$point = $proximity->first();
return redirect('create')
->withErrors(['There is already a point at that location: <a href="'.$point->getUrl().'">'.$point->name.'</a>.'])
->withInput();
}
$named = Point::where('city', $request->city)->where('name', $request->name);
if ($named->count() > 0){
$point = $named->first();
return redirect('create')
->withErrors(['There is already a <a href="'.$point->getUrl().'">'.$point->name.'</a> in '.$point->city])
->withInput();
}
$point = new Point();
DB::transaction(function() use ($request, $point){
foreach($this->fillable as $key){
$point->$key = $request->input($key);
}
$point->save();
if ($request->has('tags')){
foreach(explode(",", $request->get('tags')) as $tag){
$tag = Tag::firstOrCreate(['name' => $tag]);
$point->tags()->attach($tag);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment