PHP Laravel 发送邮件 returns 验证错误和空白字段

PHP Laravel sending mail returns validation error and empty fields

我正在构建一个 laravel-app,但当我尝试发送邮件时收到无法本地化的验证错误。

我的表单如下所示:

<form method="POST" action="{{ route('help') }}">
   <input type="hidden" name="job" value="{{ $job->id }}">
    @csrf
   <input type="text" placeholder="Name" name="name" required>
   <input type="email" placeholder="Email" name="email" required>
   <input type="tel" pattern="^[0-9-+s()]*$" placeholder="Phonenr." name="phone" required>
   <button type="submit">Send</button>
</form>

我的控制器有这个:

use Validator;
use App\Mail\HelpMail;

class HelpController extends Controller {

   public function __invoke(Request $request) {
      $validator = Validator::make($request->all(), [
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

      ...
   }
}

然后在我的帮助邮件中

class HelpMail {
   use Queueable, SerializesModels;

   public $job;
   public $name;
   public $email;
   public $phone;

   public function __construct($data) {
     $this->job = $data['job'];
     $this->name = $data['name'];
     $this->email = $data['email'];
     $this->phone = $data['phone'];
   }

}

此 returns 错误类似于:name must be filled outemail must be filled outphone must be filled out。 当我注释掉验证时,邮件通过了,但是 fields/payload 是空的,我完全不知道为什么会这样,因为我在联系表上使用了相同的方法。

我错过了什么?

所以在你使用外观的情况下,如果有任何错误,你将不得不手动处理:

$validator = Validator::make($request->all(), [
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

if ($validator->fails()) {
    // either with view, or use response()->json($validator->errors);
    return view('view_name')->withErrors($validator->errors);
} else {
    return view('view_name');
}

您可以改为对请求对象使用验证,这将 return 返回到包含错误消息包的视图:

public function __invoke(Request $request) {
      $request->validate([
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

      ...
}