How can I manually return or throw a validation error/exception in Laravel?
As of laravel 5.5, the ValidationException
class has a static method withMessages
that you can use:
$error = \Illuminate\Validation\ValidationException::withMessages([ 'field_name_1' => ['Validation Message #1'], 'field_name_2' => ['Validation Message #2'],]);throw $error;
I haven't tested this, but it should work.
Update
The message does not have to be wrapped in an array. You can also do:
use Illuminate\Validation\ValidationException;throw ValidationException::withMessages(['field_name' => 'This value is incorrect']);
Laravel <= 6.2 this solution worked for me:
$validator = Validator::make([], []); // Empty data and rules fields$validator->errors()->add('fieldName', 'This is the error message');throw new ValidationException($validator);
Simply return from controller:
return back()->withErrors('your error message');
or:
throw ValidationException::withMessages(['your error message']);