我想在验证失败时显示flash消息。 目前验证工作但闪存消息没有。 我怀疑我的条件是错误的
public function update_avatar(Request $request,$username){
$this->validate($request,[
'avatar' => 'mimes:jpeg,bmp,png|required'
]);
if($request['avatar']==null){
\Session::flash('message','Please choose a file first.');
\Session::flash('alert-class', 'alert-warning');
return redirect()->back();
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save('assets/src/uploads/avatars/' . $filename);
$user = User::where('username', $username)->first();
$user->avatar = $filename;
$user->update();
}
return redirect()->route('myplace',['username' => $user->username]);
}
修改: 表单代码已添加:
<form enctype="multipart/form-data" action="{{route('profile',['username'=>$user->username])}}" method="post">
<input type="file" size="15px" name="avatar" >
<button type="submit" name="avatar1" class="col-md-6 col-xs-6 " value="upload" style="margin-top: 20px; width: 78px !important; " >upload</button>
<input type="hidden" value="{{ csrf_token() }}" name="_token">
</form>
答案 0 :(得分:1)
尝试将FlashMessage
放入其他内容然后尝试此操作。
希望有所帮助
public function update_avatar(Request $request,$username){
$validator = Validator::make($request->all(), [
'avatar' => 'mimes:jpeg,bmp,png|required'
]);
if($validator->fails()){
\Session::flash('message','Please choose a file first.');
\Session::flash('alert-class', 'alert-warning');
return redirect()->back();
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save('assets/src/uploads/avatars/' . $filename);
$user = User::where('username', $username)->first();
$user->avatar = $filename;
$user->update();
}
return redirect()->route('myplace',['username' => $user->username]);
}
答案 1 :(得分:0)
目前您的请求未通过验证 因此要么使用laravel内置的验证,要么使用flash语句使用if语句 如果您的请求不包含头像,则由于验证失败,它将永远不会到达您的if语句。
如果您确实想在验证中创建自定义消息,请查看this链接。