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

前端 未结 5 677
我在风中等你
我在风中等你 2020-12-12 19:36

Have a method that\'s importing CSV-data into a Database. I do some basic validation using

class CsvImportController extends Controller
{
    public functio         


        
相关标签:
5条回答
  • 2020-12-12 19:54

    Simply return from controller:

    return back()->withErrors('your error message');
    
    0 讨论(0)
  • 2020-12-12 19:57

    For Laravel 5.8:

    .

    The easiest way to throw an exception is like this:

    throw new \ErrorException('Error found');
    
    0 讨论(0)
  • 2020-12-12 19:58

    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']);
    
    0 讨论(0)
  • 2020-12-12 20:16

    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);
    
    0 讨论(0)
  • 2020-12-12 20:18

    you can try a custom message bag

    try
    {
        // Call the rabbit hole of an import method
    }
    catch(\Exception $e)
    {
        return redirect()->to('dashboard')->withErrors(new \Illuminate\Support\MessageBag(['catch_exception'=>$e->getMessage()]));
    }
    
    0 讨论(0)
提交回复
热议问题