我正在构建一个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'];
}
}
这将返回错误,例如:name must be filled out
,email must be filled out
和phone must be filled out
。
当我注释掉验证时,邮件会通过,但随后的字段/有效负载为空,并且我完全不知道为什么会这样,因为我在联系表单上使用了相同的方法。
我想念什么?
答案 0 :(得分:1)
因此,在使用外墙的情况下,您将必须手动处理是否出现任何错误:
$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');
}
您可以改为对请求对象使用验证,验证将返回到视图中并带有错误消息包:
public function __invoke(Request $request) {
$request->validate([
'name' => ['required', 'string'],
'email' => ['required', 'email'],
'phone' => ['required'],
'job' => ['required', 'integer', 'exists:jobs,id'],
]);
...
}