How can I manually return or throw a validation / exception error in Laravel?

Have a method to import CSV data into a database. I do some basic checks using

class CsvImportController extends Controller
{
    public function import(Request $request)
    {   
        $this->validate($request, [
            'csv_file' => 'required|mimes:csv,txt',
        ]);

But after that, things can go wrong for more complex reasons, further down the rabbit hole, which raises exceptions. I can’t write the correct verification material that will be used here using the method validate, but I really like how Laravel works when the verification fails, and how easy it is to embed errors (errors) in the blade view, etc., so ...

Is there a (preferably clean) way to manually tell Laravel that “I know that I haven't used your method validateright now, but I would really like you to find this error here as if I did”? Is there something that I can return, an exception that I can wrap, or something else?

try
{
    // Call the rabbit hole of an import method
}
catch(\Exception $e)
{
    // Can I return/throw something that to Laravel looks 
    // like a validation error and acts accordingly here?
}
+38
source share
7 answers

Starting with laravel 5.5, the class ValidationExceptionhas a static methodwithMessages that you can use:

$error = \Illuminate\Validation\ValidationException::withMessages([
   'field_name_1' => ['Validation Message #1'],
   'field_name_2' => ['Validation Message #2'],
]);
throw $error;

I have not tested this, but it should work.

+93
source

Laravel & lt; = 6.0 this solution helped me:

$validator = Validator::make([], []); // Empty data and rules fields
$validator->errors()->add('fieldName', 'This is the error message');
throw new ValidationException($validator);
+12
source

:

return back()->withErrors('your error message');
+7

try
{
    // Call the rabbit hole of an import method
}
catch(\Exception $e)
{
    return redirect()->to('dashboard')->withErrors(new \Illuminate\Support\MessageBag(['catch_exception'=>$e]));
}
+3
source

For Laravel 5.4:

$validator = validator([], []); // Empty data and rules fields
$validator->errors()->add('fieldName', 'This is the error message');
throw new ValidationException($validator);
0
source

For Laravel 5.8:

.

The easiest way to throw an exception is this:

throw new \ErrorException('Error found');
0
source

Yes, see API docs for ValidationException

throw new \Illuminate\Validation\ValidationException($message, $code);
-1
source

All Articles