您的位置:首页 > 编程语言 > PHP开发

Laravel跳转回之前页面,并携带错误信息back()->withErrors(['错了'])

2017-11-10 15:31 585 查看

用Laravel5.1开发项目的时候,经常碰到需要携带错误信息到上一个页面,开发web后台的时候尤其强烈。

直接上:

方法一:跳转到指定路由,并携带错误信息

return redirect('/admin/resource/showAddResourceView/' . $customer_id)
->withErrors(['此授权码已过期,请重新生成!']);


方法二:跳转到上个页面,并携带错误信息

return back()->withErrors(['此激活码已与该用户绑定过!']);


方法三:validate验证(这种情况应该是最多的)

我们在提交表单的时候,进入控制器的第一步就是验证输入的参数符不符合我们的要求,如果不符合,就直接带着输入、错误信息返回到上一个页面,这个是框架自动完成的。具体例子:

$rules = [
'user_name' => 'unique:customer|min:4|max:255',
'email' => 'email|min:5|max:64|required_without:user_name',
'customer_type' => 'required|integer',
];
$messages = [
'user_name.unique' => '用户名已存在!',
'user_name.max' => '用户名长度应小于255个字符!',
'email.required_without' => '邮箱或者用户名必须至少填写一个!',
'customer_type.required' => '用户类型必填!',
];
$this->validate($request, $rules, $messages);


然后在视图里面引入公共的错误信息:

D:\phpStudy\WWW\xxx\resources\views\admin\error.blade.php

<div class="form-group">
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul style="color:red;">
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
</div>


例如:

@extends('admin.master')
@section('css')
@parent
<link href="{{ asset('css/plugins/iCheck/custom.css') }}" rel="stylesheet">
@endsection
@section('content')
{{-- {{dd($data)}} --}}
<div class="wrapper wrapper-content animated fadeInRight">
@include('admin.error')


如果还需要自定义错误信息,并且把之前传过来的值返回到上一个视图,还需要加个withInput;

if (empty($res)) {
return back()->withErrors(['查不到这个用户,请检查!'])->withInput();
}


实际展示效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redirect web
相关文章推荐