laravel - 如何创建自定义消息包,错误数组

时间:2018-06-15 22:32:12

标签: laravel

我正在尝试制作自定义消息包但无法制作,我想使用$ errors

$errorMsgs = [];
    if (Model::where('name', '=', Input::get('name'))->exists()) {
       $errorMsgs['company_name'] = 'name already exists';

    }else if (Model::where('age', '=', Input::get('age'))->exists()) {
        $errorMsgs['primary_phone'] = 'age no already exists';

    }else if (Model::where('mobile', '=', Input::get('mobile'))->exists()) {
        $errorMsgs['primary_mobile'] = 'mobile already exists';

    }else if (Model::where('pri_email', '=', Input::get('primary_email'))->exists()) {
        $errorMsgs['primary_email'] = 'Primary email already exists';

    }else{
// success 


        }

实际上我想使用foreach错误

 @if ($errors->any())
               <div class="alert alert-danger">
                   <ul>
                       @foreach ($errors->all() as $error)
                           <li>{{ $error }}</li>
                       @endforeach
                   </ul>
               </div>
           @endif

1 个答案:

答案 0 :(得分:1)

我无法从你的问题中看出为什么开箱即用的unique Validation没有被使用,它似乎正是为了这个目的。无论如何,手动方式的要点就像......

// Controller
public function WhatEverController()
{
    $data = [];

    $errorMsgs = [];
    if (Model::where('name', '=', Input::get('name'))->exists()) {
       $errorMsgs['company_name'] = 'name already exists';

    }
    if (Model::where('age', '=', Input::get('age'))->exists()) {
        $errorMsgs['primary_phone'] = 'age no already exists';

    }
    if (Model::where('mobile', '=', Input::get('mobile'))->exists()) {
        $errorMsgs['primary_mobile'] = 'mobile already exists';

    }
    if (Model::where('pri_email', '=', Input::get('primary_email'))->exists()) {
        $errorMsgs['primary_email'] = 'Primary email already exists';
    }

    if(count($errorMsgs)) {
        return  redirect()->back()->withErrors($errorMsgs);
    }

    return view('someview');
}


// Blade
@if(count($errors))
<div class="alert alert-danger">
    <ul>
        @foreach ($errors as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

使用if/elseif时,还有一个细节,它将始终在第一场比赛中停止,因此总是最多只有一个$errorMsg。我已将其更改为多个if语句,因为这将提供获取错误数组的机会。