1

I have a small question. I create simple API using Laravel. When I use validation and if it fails, I got a common message:

{
"result": false,
"message": "The given data failed to pass validation.",
"details": []
}

But how can I get details about which field fails and why like that:

{  
   "result":false,
   "message":"The given data failed to pass validation.",
   "details":{  
      "email":[  
         "The email field is required."
      ],
      "password":[  
         "The password must be at least 3 characters."
      ]
   }
}

My code in controller looks like this:

protected function validator(array $data)
{
    $validator = Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:3',
    ]);

    return $validator;
}

protected function create(array $data)
{

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'role_id' => 2
    ]);
}

5 Answers 5

2

It is better to handle the validator within the same process, like this:

public function register(Request $request){
    $validator =  Validator::make($request->all(),[
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:users',
    'password' => 'required|string|min:6|confirmed',
    ]);

    if($validator->fails()){
        return response()->json([
            "error" => 'validation_error',
            "message" => $validator->errors(),
        ], 422);
    }

    $request->merge(['password' => Hash::make($request->password)]);

    try{
        $user = User::create($request->all());
        return response()->json(['status','registered successfully'],200);
    }
    catch(Exception $e){
        return response()->json([
            "error" => "could_not_register",
            "message" => "Unable to register user"
        ], 400);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You should make sure you're sending the request with the Accept: application/json header.

Without that - Laravel won't detect that it's an API request,

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

check the documentation

Comments

1

I used validate in my project:

1.I created app/http/requests/CreateUserRequestForm.php

public function rules()
    {
        return [
            "name"       => 'required',
            "address"    => 'required',
            "phnumber"   => 'required|numeric',

        ];
    }

    public function messages()
    {
        return [
            'name.required'     => 'Please Enter Name',
            'addresss.required' => 'Please Enter Address',
            'phnumber.required' => 'Please Enter PhNumber'

        ];
    }
  1. call the RequestForm in controller

use App\Http\Requests\CreateUserRequestForm;

public function createUser(CreateUserRequestForm $request)
    {
        // create       
        $user= UserModel::create([
            'name'      => $request->input('name'),
            'address'   => $request->input('address'),
            'phnumber'  => $request->input('phnumber')

        ]);      

        return response()->json(['User' => $user]);
    }

Comments

0

Try this i didn't try but it should be work for you.

You may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated.

take reference from here. laravel validation

/**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('email', 'Please enter valid email id');
            }
        });
    }

4 Comments

If explore my validation object, i see that i have these messages already, And my question is how to change standard laravel error message "The given data failed to pass validation." to something more detailed.
got it....can u please show code from where u returning your response..
which Laravel version you are using..? please see the /storage/logs/laravel.log is there any error regarding validation.
lastest All my code in the question. It placed in the standard RegisterController.php.
0

Try this:

    public function create(){
     
       // ------ Validate -----
       $this->vallidate($request,[
             'enter code here`name' => 'required|string|max:255',
             'email' => 'required|string|email|max:255|unique:users',
             'password' => 'required|string|min:3'
       ]);

       // ------ Create user -----
       $user = User::create(['name' => $request->name']);

       return response()->json([
           'message' => "success",
           'data'    => $user``
       ]);
     }

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.