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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM