用Laravel5.1開發(fā)項目的時候,經(jīng)常碰到需要攜帶錯誤信息到上一個頁面,開發(fā)web后臺的時候尤其強烈。
	方法一:跳轉(zhuǎn)到指定路由,并攜帶錯誤信息
	return redirect('/admin/resource/showAddResourceView/' . $customer_id)
	    ->withErrors(['此授權(quán)碼已過期,請重新生成!']);
	方法二:跳轉(zhuǎn)到上個頁面,并攜帶錯誤信息
	return back()->withErrors(['此激活碼已與該用戶綁定過!']);
	方法三:validate驗證(這種情況應(yīng)該是最多的)
	 
	我們在提交表單的時候,進入控制器的第一步就是驗證輸入的參數(shù)符不符合我們的要求,如果不符合,就直接帶著輸入、錯誤信息返回到上一個頁面,這個是框架自動完成的。具體例子:
	$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' => '用戶名長度應(yīng)小于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();
	}
	實際展示效果如下:
	![Laravel跳轉(zhuǎn)回之前頁面,并攜帶錯誤信息back()->withErrors(['錯了'])](/uploads/allimg/190110/1-1Z1101H335.jpg)
	 
                    ![Laravel跳轉(zhuǎn)回之前頁面,并攜帶錯誤信息back()->withErrors(['錯了'])](/uploads/allimg/190110/1-1Z1101H335.jpg)



 鄂公網(wǎng)安備 42090202000212號
鄂公網(wǎng)安備 42090202000212號