Laravel跳转回之前页面,并携带错误信息

用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();
}
效果如下:

 

 

 

转自:https://blog.csdn.net/zhezhebie/article/details/78500326

posted @ 2018-04-04 15:44  郁冬  阅读(6410)  评论(0编辑  收藏  举报