废话不多说,上代码!!!
return back()->withErrors($validate)->withInput();
页面对应方法:
@error('image')
<div class="alert alert-danger">{{$message}}</div>
@enderror
return back()->withInput()->withErrors('请上传图片!', 'image');
页面对应方法:
@if(count($errors->image) > 0)
<divclass="alert alert-danger">{{ $errors->image->first() }}</div>
@endif
下面是实例:
controller 代码部分:
//添加图书方法
public function store(Request $request)
{
$book = $request->all(); //获取全部传参
//定义验证规则
$rules = [
'book_name'=>'required|min:3|max:50',
'image'=>'required|image',
'content'=>'required',
];
//自定义规则提示语
$message = [
'book_name.required'=>'书名不能为空',
'book_name.min'=>'书名太短,至少要有:3个字符',
'book_name.max'=>'书名太长,最多不超过:50个字符',
'image.required'=>'请上传图片',
'image.image'=>'上传的文件不是图片类型',
'content.required'=>'简介不能为空',
];
//规则验证
$validate = Validator::make($book, $rules, $message);
if($validate->fails()){
return back()->withErrors($validate)->withInput();
}
//如果上面有image 验证规则,则不需要此方法
//判断是否有图片上传 - 单独验证方法,指定变量名的错误输出
//页面使用 {{ $errors->image->first() }} 获取到错误信息
if (!$request->hasFile('image')) {
return back()->withInput()->withErrors('请上传图片!', 'image');
}
//判断图片上传合法性
if (!$request->file('image')->isValid()) {
return back()->withInput()->withErrors('上传图片失败,请检查保存目录权限!', 'image');
}
//执行图片上传
$image = $request->file('image')->store('image');
$book['image'] = $image;
Book::create($book); //模型插入数据库
return redirect('/book');
}
view页面代码部分:
<h2>添加图书信息</h2>
<form method="post" class="form-x" action="/book" enctype="multipart/form-data">
@csrf
<table class="profile-table">
<tr>
<th>书名:</th>
<td>
<!-- {{ old('变量名') }} 此方法是提交后拿到提交前的数据 -->
<input type="text" name="book_name" value="{{ old('book_name')}}" />
<!-- @error('变量名') 这里是controller 验证规则的变量名 -->
@error('book_name')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</td>
</tr>
<tr>
<th>图片:</th>
<td>
<input type="file" name="image"/>
<!-- if 这里是 controller withErrors('xxxxx', '变量名'); 自定义输出错误信息使用的 -->
@if(count($errors->image) > 0)
<div class="alert alert-danger">{{ $errors->image->first() }}</div>
@endif
@error('image')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</td>
</tr>
<tr>
<th>简介:</th>
<td>
<textarea name="content">{{ old('content')}}</textarea>
@error('content')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</td>
</tr>
<tr>
<td colspan="2" class="td-btn">
<input type="submit" value="提 交" class="button"/>
<input type="reset" value="重 置" class="button"/>
</td>
</tr>
</table>
</form>