2017-08-12 200 views
0

問:如何重新從另一個控制器驗證的ResigsterController驗證規則,而不必抓住整個RegisterController類?
下面是規則:重用laravel驗證規則

... 

protected function validator(array $data) 
{ 
    return Validator::make($data, [ 
     'fname' => 'required|string|max:255', 
     'lname' => 'required|string|max:255', 
     'email' => 'required|string|email|max:255|unique:users', 
     'password' => 'required|string|min:6|confirmed', 
     'tos' => 'boolean|accepted', 
    ]); 
} 
... 

中的其他控制器:
應用程序\ HTTP \控制器\ UserController.php

public function update(Request $request, User $user) 
{ 
    //I need to validate $request with the rules from 
    //ControllersAuth\RegisterController.php 
} 
+1

你可以創建一個表單請求驗證和使用時,你需要... –

+0

檢查我的答案,如果你想與特質,謝謝 –

回答

0

你應該嘗試使用創建一個Helper類,所以你可以有一些代碼可以在任何類中重用。

如果你不知道如何做一個Helper類有導遊here

0

你可以做一個文件請求添加驗證規則存在,下一次u需要它,你可以調用的文件名,前:

public function update(UserRequest $request,User $user){ 
} 



//1. Php artisan make:request UserRequest 
//2. add rule to UserRequest file 
public function rules() 
     { 
      return [ 
       'fname' => 'required|string|max:255', 
      'lname' => 'required|string|max:255', 
      'email' => 'required|string|email|max:255|unique:users', 
      'password' => 'required|string|min:6|confirmed', 
      'tos' => 'boolean|accepted', 
      ]; 
     } 

https://laravel.com/docs/5.4/validation#form-request-validation

0

我建議使用特點。 創建一個特質,如:

trait ValidationTrait { 
    public $errors; 

    public function validate($data) { 
     $Reflection = new \ReflectionClass(__CLASS__); 
     $ReflectionClass = $Reflection->newInstance(); 
     if(empty($ReflectionClass->rules)) return TRUE; 

     $v = Validator::make($data, $ReflectionClass->rules); 

     if($v->fails()) { 
      $this->errors = $v->failed(); 
      return FALSE; 
     } 

     return TRUE; 
    } 

    public function validationErrors() { 
     return $this->errors; 
    } 
} 

在模型:

class myModel extends Eloquent { 
    use ValidationTrait; 

    public $rules = array(
     'fname' => 'required|string|max:255', 
     'lname' => 'required|string|max:255', 
     'email' => 'required|string|email|max:255|unique:users', 
     'password' => 'required|string|min:6|confirmed', 
     'tos' => 'boolean|accepted', 
    ); 
} 

這樣稱呼它:

$myModel = new myModel(); 

if($myModel->validate(Input::all()) { 
    //validate success.... 
}else{ 
    return $Customer->validationErrors() 
} 

希望這可以幫助你順利!