2017-09-29 9 views
1

は、だから私は基本的なフォームを持っているの要求にルールの別のルールから値だ、のは、例えばとしましょう:属性を渡すと、それは

<form action="" method="POST" role="form"> 
    <legend>Form title</legend> 

    <div class="form-group"> 
     <label for="">label</label> 
     <input type="text" name="main" class="form-control" id="" placeholder="Input field"> 
    </div> 

    <div class="form-group"> 
     <label for="">label</label> 
     <input type="text" name="test" class="form-control" id="" placeholder="Input field"> 
    </div> 

    <button type="submit" class="btn btn-primary">Submit</button> 
</form> 

さて、私のコントローラのメソッド内で、私は要求を使用しています:

public function store(CreateTestRequest $request) 
{ 

} 

さて、私の要求ファイル内に、私はのは、テスト入力しましょうのルールを持っている:

/** 
* Get the validation rules that apply to the request. 
* 
* @return array 
*/ 
public function rules() 
{ 
    return [ 
     'main'  => 'required', 
     'test'  => [ 
      'required', 
      'numeric', 
      new \App\Rules\Account\MyCustomRule, 
     ], 
    ]; 
} 

内部myCustomRuleを、私はトラインよgのメインの属性と値、そしてテストの属性と値の両方にアクセスするには、デフォルトでテストのアクセントにすることができますが、他の入力の名前と値をカスタムルールに渡す方法がわかりません...可能?もしそうなら、どうしたらいいですか?

<?php 

namespace App\Rules\Account; 

use Illuminate\Contracts\Validation\Rule; 

class MyCustomRule implements Rule 
{ 
    /** 
    * Create a new rule instance. 
    * 
    * @return void 
    */ 
    public function __construct() 
    { 
    } 

    /** 
    * Determine if the validation rule passes. 
    * 
    * @param string $attribute 
    * @param mixed $value 
    * @return bool 
    */ 
    public function passes($attribute, $value) 
    { 
     dd($value); 
    } 

    /** 
    * Get the validation error message. 
    * 
    * @return string 
    */ 
    public function message() 
    { 
     return 'Sorry. '; 
    } 
} 

答えて

0

ルールオブジェクトをインスタンス化してコンストラクタでアクセスするときに、パラメータを渡すことができます。あなたのルールで

new \App\Rules\Account\MyCustomRule($this->main), 

:フォームリクエストで

- 更新

protected $main; 

public function __construct($main) 
{ 
    $this->main = $main; 
} 

public function passes($attribute, $value) 
{ 
    // You can now access $this->main for whatever logic you need 
    return $value === $this->main; 
} 
+0

$要求 - >メインはヌル –

+0

@randommman申し訳ありませんおっとを返すようです。 –

関連する問題