0712-2888027 189-8648-0214
微信公眾號

孝感風信網(wǎng)絡科技有限公司微信公眾號

當前位置:主頁 > 技術支持 > PHP > Laravel跳轉回之前頁面,并攜帶錯誤信息back()->withErrors(['錯了'])

Laravel跳轉回之前頁面,并攜帶錯誤信息back()->withErrors(['錯了'])

時間:2024-09-20來源:風信官網(wǎng) 點擊: 2261次
用Laravel5.1開發(fā)項目的時候,經常碰到需要攜帶錯誤信息到上一個頁面,開發(fā)web后臺的時候尤其強烈。
 
方法一:跳轉到指定路由,并攜帶錯誤信息
 
return redirect('/admin/resource/showAddResourceView/' . $customer_id)
    ->withErrors(['此授權碼已過期,請重新生成!']);
 
方法二:跳轉到上個頁面,并攜帶錯誤信息
 
return back()->withErrors(['此激活碼已與該用戶綁定過!']);
 
方法三:validate驗證(這種情況應該是最多的)
 
我們在提交表單的時候,進入控制器的第一步就是驗證輸入的參數(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' => '用戶名長度應小于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跳轉回之前頁面,并攜帶錯誤信息back()->withErrors(['錯了'])
 
欄目列表
推薦內容
熱點內容
展開