0

I'm having an address field in my form,by using the address given I fetch that lat & long for that and save it into DB..

If the user enter's wrong address the lat & long would be null..

So here I need to add a new validator rule for that field..

Here is my code,

I tried something like this..But Don't know how to do this..

public function getLatlan( $address = '')
{
    $formattedAddr = str_replace(' ','+',$address);
    $geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false'); 
    $output = json_decode($geocodeFromAddr);
    $data['latitude']  = $output->results[0]->geometry->location->lat; 
    $data['longitude'] = $output->results[0]->geometry->location->lng;
    return $data;
}

function postSave( Request $request)
{

    $rules = $this->validateForm();
    $address_validate   = array('location'      =>'enter valid address');

    if($_REQUEST['location'] != ''){
        $data = $this->getLatlan($_REQUEST['location']);
    }
    if($data['latitude'] == '' || $data['longitude'] == ''){
        array_merge($rules,$address_validate);
    }
    $validator = Validator::make($request->all(), $rules);
    if ($validator->passes()) {
        ..
    }
}

How should I do this... Could someone help me..

Thank you,

3
  • Have you read this laravel.com/docs/5.2/validation#custom-validation-rules Commented Aug 8, 2016 at 7:22
  • Yes I did it..But don't know how to implement this in my case.. Commented Aug 8, 2016 at 7:28
  • Why not? You just have to extract your lat and long validation into a custom rule. I think the documentation is very good and understandable. Commented Aug 8, 2016 at 7:35

1 Answer 1

3

You've need to create request validation Class new form Request.

  1. Create New Request Class

App/Requests/MapRequest.php
and

namespace App\Http\Requests;
use App\Http\Requests\Request;
class MapRequest extends Request
{
    public function rules()
    {
        return [
            'lat' => 'required|min:2',
            'long' => 'required',
        ];
    }
    public function messages()
    {
        return [
            'lat.required' => 'Required Message',
            'lat.min' => 'Minimum value message',
            'long.required' => 'Required Message'
        ];
    }
}
  1. Use Map Request class into your controller method: for example, MapController:

    public function store(MapRequest $request)
    {
         // process your logic to here! 
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.