Home > Enterprise >  custom validation error message from a controller in laravel8
custom validation error message from a controller in laravel8

Time:10-13

protected function validator(array $data)
{
    $validation = Validator::make($data, [
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed']
    ]);
    if ($validation->fails())
    { 
        return session()->flash('alert-danger', 'error');
    }
}

protected function create(array $data)
{
    $company = new Company();
    $company->store_name = $data['company_name'];
    $company->save();
}

Check the fail status inside the validator function and show the error message

CodePudding user response:

 request()->validate([
        'email' => 'required'
    ],
    [
        'email.required' => 'You have to choose the email!',
    ]);

CodePudding user response:

try this below code instead of the above validation

request()->validate([
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ];

now if you remove the code

   if ($validation->fails())
        { 
            return session()->flash('alert-danger', 'error');
        }

the code will run without any error . and if you do not enter any value in the input field the the request->validate() will check all the request.

CodePudding user response:

You need to actually return something in your if ($validation->fails()) check. Right now, you're setting a session Flash, but returning null (->flash() has no return value).

You have a couple solutions here, but it depends if this is a Form Submission or an AJAX Request:

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

protected function create(array $data) {
  $validator = $this->validator($data);

  if ($validator->fails()) {
    session()->flash('alert-danger', 'error');
    
    // If this is an AJAX Request:
    if (request()->ajax()) {
      return response()->json(['errors' => $validator->errors()], 422);
    }

    // If this is a Form Submission:
    return back()->withErrors($validator->errors());
  } 

  $company = new Company();
  $company->store_name = $data['company_name'];
  $company->save();
}

Basically, modify your validator method to return the Validator::make() instance, check it in your create() method, and return appropriately based on if this is an AJAX Request or Form Submission.

  • Related