现在我正在学习laravel。
我有一个问题: Blade,不想显示验证器错误。
我创建请求“ContactRequest”:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ContactRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'required',
];
}
public function messages()
{
return [
'name.required' => 'Er, you forgot your name!',
];
}
}
只需为页面设置控制器即可。
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests\ContactRequest;
use App\Http\Controllers\Controller;
use Validator;
class ContactController extends Controller
{
public function store(ContactRequest $request) {
return view('default.contact',['title'=>'Contacts']);
}
public function show()
{
return view('default.contact',['title'=>'Contacts']);
}
}
只需在$ middleware
的属性中添加正确的提供商:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
创建了2个路由器:
Route::get('/contact',['uses'=>'Admin\ContactController@show','as'=>'contact']);
Route::post('/contact',['uses'=>'Admin\ContactController@store']);
(试图将它们组合成一组middleware => web
(没有帮助))
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="form-area">
<form method="post" action="{{ route('contact') }}">
{{ csrf_field() }}
<div class="form-group">
<input type="text" class="form-control" value="{{ old('name') }}" id="name" name="name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" class="form-control" value="{{ old('email') }}" id="email" name="email" placeholder="Email">
</div>
<div class="form-group">
<input type="text" class="form-control" value="{{ old('site') }}" id="site" name="site" placeholder="site">
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" name="text" id="message" placeholder="Message" maxlength="140" rows="7">{{ old('text') }}</textarea>
<span class="help-block"><p id="characterLeft" class="help-block ">You have reached the limit</p></span>
</div>
<input type="submit" id="submit" name="submit" class="btn btn-primary">
</form>
</div>
但最后,提交表单时,不会显示错误消息。请告诉我该怎么办?谢谢。
答案 0 :(得分:0)
如果验证失败,您可以重定向错误:
$validator=Validator::make($request->all(),[
'name'=>'required']);
if($validator->fails())
{
return redirect("/contact")->withErrors($validator);
}
然后,在视图中:
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif