skip to Main Content

i am trying to get the validations errros on signup but the flutter is just showing error code with the string but as we know laravel send whole array of errors which i am unable to get

here is my code

on<SignUpUser>( (event, emit) async {
          final dio = getIt<Dio>();
          dynamic result = await dio.post('/api/register', data: {
            'name': event.name,
            'email': event.email,
            'password': event.password,
            'password_confirmation': event.passwordConfirmation
          },
            options: Options(
              // followRedirects: false,
              // maxRedirects: 0,
              // validateStatus: (status) => status! < 500,
              headers: {
                "Accept" : "application/json",
                "Content-Type":"application/json"
              },
            ),

          );
          // print(result.body);
          if(result.statusCode == 422){
            print(result.body['errors']); //print out validation errors
          }
    });

i have tried most of the stuff but not getting any understanding on this

2

Answers


  1. Chosen as BEST ANSWER

    you can simply use DioExceptions like this

    static dynamic globalRequest(url, data, method, [headers]) async {
    if (headers == null) {
      Map<String, dynamic> headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
      };
      final dio = getIt<Dio>();
      try {
        dynamic result = await dio.request(
          '/api/$url',
          data: data,
          options: Options(
            method: method,
            headers: headers,
          ),
        );
        return result;
      } on DioException catch  (e) {
        return e.response;
      }
    }
    

    }

    on<SignUpUser>((event, emit) async {
        Map<String, dynamic>data= {
          'name': event.name,
          'email': event.email,
          'password': event.password,
          'password_confirmation': event.passwordConfirmation
        };
        final result= await GlobalRequest.globalRequest('register',data,'post');
        print(result);
    });
    

  2. but as we know laravel send whole array of errors[...] – I don’t think that’s true. Sending a 422 with no body should be the default behavior and is also the most secure thing to do. You can, however, return the the errors explicitly by adding a FormRequest with a function like this one:

    protected function failedValidation(Validator $validator) {
        if ($this->expectsJson()) {
            $errors = (new ValidationException($validator))->errors();
            throw new HttpResponseException(
                response()->json(['data' => $errors], 422)
            );
        }
        parent::failedValidation($validator);
    }
    

    See similar discussion here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search