2017-05-12 39 views
1

是否有任何方式自動顯示錯誤信息?就像它在CodeIgniter中一樣? 我有一個接觸的形式,如果它的驗證錯誤,我做:Laravel聯繫人模板錯誤

  return Redirect::to('/support/contact') 
     ->with('message', 'Feedback must contain more than 5 characters. Try Again.'); 

我的規則,我的領域:

 $rules = array (
     'first_name' => 'required', 
     'email' => 'required|email', 
     'message' => 'required|min:5' 
    ); 

這是任何方式,根據我的領域,使汽車的消息?

我的控制器:

<?php 
namespace App\Http\Controllers; 

use Input; 
use Illuminate\Http\Request; 
use Validator; 
use Mail; 
use Redirect; 

class ContactController extends Controller 
{ 
public function getContactUsForm(){ 

     $data = \Input::all(); 

     $rules = array (
      'first_name' => 'required', 
      'email' => 'required|email', 
      'message' => 'required|min:5' 
     ); 

     $validator = Validator::make ($data, $rules); 

     if ($validator -> passes()){ 
      Mail::send('emails.contact', $data, function($bodyMessage) use ($data) 
      { 
       $bodyMessage->from($data['email'] , $data['first_name']); 



    $bodyMessage->to('[email protected]', 'He')->subject(' Contact Form'); 

       }); 
     return Redirect::to('/support/contact') 
     ->with('message', 'Your message has been sent. Thank You!'); 


      }else{ 
      return Redirect::to('/support/contact') 
      ->with('message', 'Feedback must contain more than 5 characters. Try Again.'); 

     } 
    } 
    } 
+0

是的,但您如何定義郵件取決於您如何應用規則。你使用控制器'$ this-> validate()'方法,你使用表單請求驗證還是手動創建你自己的驗證器實例?請顯示更多代碼。 – jfadich

+0

@jfadich發佈了我的控制器代碼 – Rost

回答

0

完全容易做到。

一種方法是改變你的$驗證器使用的消息的另一個陣列:

實施例:

$validator = Validator::make($request->all(), 
     [ 
      'first_name'   => 'required', 
      'email'     => 'required|email', 
      'message'    => 'required|min:5' 
     ], 
     [ 
      'first_name.required'  => 'First Name is required', 
      'email.required'   => 'Email is Required.', 
      'email.email'    => 'Not a valid email', 
      'message.max'    => 'Message is Required.', 
      'message.min'    => 'Message must me at least 5 characters.', 
     ] 
    ); 

另一種方法是通過的消息作爲第三arguement

$messages = [ 

      'first_name.required'  => 'First Name is required', 
      'email.required'   => 'Email is Required.', 
      'email.email'    => 'Not a valid email', 
      'message.max'    => 'Message is Required.', 
      'message.min'    => 'Message must me at least 5 characters.', 

] 

$validator = Validator::make ($data, $rules, $messages); 

https://laravel.com/docs/5.4/validation#custom-error-messages

您可能還想檢查t他的驗證失敗,而不是取得成功,用下面的代替你的if/else,然後在方法底部有'快樂的路徑'。

if ($validator->fails()) { 

     // Or do custom action here with $request, $validator 

     $this->throwValidationException(
      $request, $validator 
     ); 
    } 
+0

非常感謝! – Rost