Jacobo
Jacobo

Reputation: 1391

Laravel throw a custom ValidationException

I'm trying to throw a custom exception. The project is an API consuming the Google Places API, and if the result has a status of ZERO RESULTS I need to throw a validation exception. This is because the stored data is wrong.

To be more clear about this. A registered user modifies his profile which includes address, zip code, etc. Then we have a get method in which we make a query to the places API, this in order to get the latitude and longitude and add it to the profile model.

if (strcmp($status, 'ZERO_RESULTS') == 0 || strcmp($status, 'INVALID_REQUEST') == 0) {
    $error = ValidationException::withMessages([
        "one_thing" => ["Validation Message #1"], "another_thing" => ['Validation Message #2']
    ]);
    throw $error;
}

I read some answers on StackOverflow and I'm even trying those answers but I'm only getting the following error:

{
  "errors": [
    {
      "status": 500,
      "code": 1,
      "source": {
        "pointer": "ErrorException line 73 in /Users/jacobotapia/Documents/Espora/one-mind-backend/vendor/sfelix-martins/json-exception-handler/src/ValidationHandler.php"
      },
      "title": "errorexception",
      "detail": "Undefined index: one_thing"
    }
  ]
}

Also I want to point that all the process occurs during a GET method.

The only thing that I want is to return an error saying that we could not get any result from the google places API. This with the objective to say to the client that the profile data that the user registered in the app is wrong.

What am I doing wrong?

Upvotes: 3

Views: 10841

Answers (2)

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9703

May be you would like to try if you have field names "one_thing" and "another_thing"

$error = Illuminate\Validation\ValidationException::withMessages([
        "one_thing" => ["Validation Message #1"], 
        "another_thing" => ['Validation Message #2']
    ]);

throw $error;

check the withMessages() method definition

 public static function withMessages(array $messages)
    {
        return new static(tap(ValidatorFacade::make([], []), function ($validator) use ($messages) {
            foreach ($messages as $key => $value) {
                foreach (Arr::wrap($value) as $message) {
                    $validator->errors()->add($key, $message);
                }
            }
        }));
    }

The keys are treated as fields name, so that the $errors you will through will be related to respective fields.

so basically like

$error = \Illuminate\Validation\ValidationException::withMessages([
   'field_name_1' => ['Validation Message for field name 1'],
   'field_name_2' => ['Validation Message for field name 2'],
   'field_name_3' => ['Validation Message for field name 3'],
]);
throw $error;

Try this

Form code is

<form action="{{ route('test-validation') }}" method="POST">
    @csrf
    <input type="text" name="test" value="" />
    @if( $errors->has('test') ) 
        @foreach( $errors->get('test') as $err ) 
            {{ $err  }} 
        @endforeach 
    @endif
    <input type="submit" name="submit" value="Submit" />
 </form>

and in your routes/web.php

use Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
Route::post('test-validation', function(Request $request){

    $fields = array('test' => $request->input('test'));
    $rules = array('test' => 'required|min:5');

    $validator = Validator::make($fields, $rules); // Empty data and rules fields
    $validator->errors()->add('test', 'This is the error message for test field');
    throw new ValidationException($validator);

    redirect()->withErrors($validator);
})->name('test-validation');

With this code you should be able to get the errors correctly.

Upvotes: 8

Ravindra Bhanderi
Ravindra Bhanderi

Reputation: 2936

Here is the solution of your probleam

Solution 1: send error message with http code

return response()->json(["error"=> "YOUR_MESSAGE_HERE"],401);

Laravel - Return json along with http status code

Upvotes: -4

Related Questions