1. 程式人生 > >Laravel跳轉回之前頁面,並攜帶錯誤資訊back()->withErrors(['錯了'])

Laravel跳轉回之前頁面,並攜帶錯誤資訊back()->withErrors(['錯了'])

用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();
}

實際展示效果如下:

這裡寫圖片描述