我有一个像这样的控制器方法:
use Validator;
public function insert(Request $request)
{
$data = Validator::make(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
])->validated();
$wallet = new Wallet();
$wallet->title = $data['title'];
$wallet->name = $data['name'];
if (!empty($data['activation'])) {
$wallet->is_active = 1;
} else {
$wallet->is_active = 0;
}
if (!empty($data['cachable'])) {
$wallet->is_cachable = 1;
} else {
$wallet->is_cachable = 0;
}
$wallet->save();
return redirect(url('admin/wallets/index'));
}
然后我尝试显示这样的错误:
@error("name")
<div class="alert alert-danger">{{$message}}</div>
@enderror
但问题是,当我填写错误时,它不会打印任何错误。
那么如何解决这个问题并正确显示错误?
这是表单本身,但它正确地将数据提交给数据库:
<form action="{{ route('insertWallet') }}" method="POST" enctype="multipart/form-data">
@csrf
<label for="title" class="control-label">Title</label>
<br>
<input type="text" id="title-shop" name="title" class="form-control" value="" autofocus>
@error("title")
<div class="alert alert-danger">{{$message}}</div>
@enderror
<label for="title" class="control-label">Name</label>
<br>
<input type="text" id="title-shop" name="name" class="form-control" value="" autofocus>
@error("name")
<div class="alert alert-danger">{{$message}}</div>
@enderror
<input class="form-check-input" type="checkbox" name="cachable" value="cashable" id="cacheStatus">
<label class="form-check-label" for="cacheStatus">
With Cash
</label>
<input class="form-check-input" type="checkbox" name="activaton" value="active" id="activationStatus">
<label class="form-check-label" for="activationStatus">
Be Active
</label>
<button class="btn btn-success">Submit</button>
</form>
答案 0 :(得分:1)
查看官方文档here
添加以下代码
if($data->fails()){
return redirect(url('admin/wallets/index'))->withErrors($data)->withInput();
}
然后将数据保存在数据库中
答案 1 :(得分:0)
您没有返回任何错误,您只是在没有任何数据的情况下重定向回视图。
您的解决方法是让您的验证器如下:
$data = Validator::validate(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
]);
看到我已将 Validator::make
更改为 Validator::validate
。正如 documentation 所述:
如果验证规则通过,您的代码将继续正常执行;但是,如果验证失败,则会抛出异常并自动将正确的错误响应发送回用户。
<块引用>如果在传统 HTTP 请求过程中验证失败,则会生成对前一个 URL 的重定向响应。如果传入请求是 XHR 请求,则将返回包含验证错误消息的 JSON 响应。
所以,如果你的验证通过,它会将所有验证过的数据保存到 $data
中,就像你对 ->validated()
所做的一样(但你不必在这里写),如果失败,它会自动抛出一个异常,在这种情况下是 ValidationException
,所以 Laravel 会自动处理它并重定向回到相同的 URL 和 errors
。所以它现在应该可以工作了...
This is the Validator::validate
source code 和 this is the validate
source code 用于 validator validate
方法。