skip to Main Content

I am trying to validate the form using this way:

// Start validation 
$validator = Validator::make($request->all(), [
    'project_token'     =>  'required',
    'user_id'           =>  'required',
    'competitor_name'   =>  'required',
    'competitor_domain' =>  ['required','regex:/^(?!(www|http|https).)w+(.w+)+$/'],
    'status'            =>  'required',
]);

// If validation is not sucessfull
if( $validator->fails() ) {
    return response()->json([
        'success'   =>  false,
        'message'   =>  $validator->withErrors($validator)
    ], 200);
} else {
    ....
}

If the validation is failed I want to get the error messages in the message key. How can I get the error messages ? Its showing me an error message:

Method IlluminateValidationValidator::withErrors does not exist.

2

Answers


  1. You have to use a validator error like this

    if( $validator->fails() ) {
        return response()->json([
            'success'   =>  false,
            'message'   =>  $validator->errors()
        ], 200);
    }
    

    Or

    $validator->errors()->all(); # as a Array
    
    Login or Signup to reply.
  2. Try this, It will return proper validation message and check the validation on defined field.

     $request->validate([
        'project_token'     =>  'required',
        'user_id'           =>  'required',
        'competitor_name'   =>  'required',
        'competitor_domain' =>  ['required','regex:/^(?!(www|http|https).)w+(.w+)+$/'],
        'status'            =>  'required',
    ], [
      'project_token.required' => 'Please Generate Project token'
    ]);
    

    in your blade file if you add this condition after each element then if any validation error acure then it will show in front with custom message

     @if ($errors->has('project_token'))
          <span class="text-danger">{{ $errors->first('project_token') }}</span>
     @endif
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search