做法 With 設計一個檢查請求參數是否符合特定關聯的驗證規則,例如可接受 projects
和 environments
參數,則以下請求將通過驗證:
1 2 3 4 api/users/me/projects?with=projects api/users/me/projects?with=environments api/users/me/projects?with=projects,environments api/users/me/projects?with=environments,projects
新增 With
驗證規則。
1 php artisan make:rule With
修改 app/Rules/With.php
檔。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 namespace App \Rules ;use Illuminate \Contracts \Validation \Rule ;class With implements Rule { protected $values ; public function __construct ($values ) { $this ->values = $values ; } public function passes ($attribute , $value ) { if (! $value ) { return true ; } $values = explode (',' , $value ); foreach ($values as $value ) { if (! in_array ($value , $this ->values, true )) { return false ; } } return true ; } public function message ( ) { return 'The :attribute must be the following types: ' .implode (', ' , $this ->values).'.' ; } }
在 app/Http/Requests/ProjectRequest.php
檔使用。
1 2 3 4 5 6 7 8 9 public function rules ( ) { return [ 'with' => new With ([ 'users' , 'environments' , ]), ]; }
Unique 設計一個檢查使用者是否已有相同名稱資源的驗證規則。
新增 Unique
驗證規則。
1 php artisan make:rule Unique
修改 app/Rules/Unique.php
檔。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 namespace App \Rules ;use Illuminate \Contracts \Validation \Rule ;class Unique implements Rule { protected $user ; protected $table ; public function __construct ($user , $table ) { $this ->user = $user ; $this ->table = $table ; } public function passes ($attribute , $value ) { $table = $this ->table; if ($this ->user->$table ()->where ($attribute , $value )->first ()) { return false ; } return true ; } public function message ( ) { return 'The :attribute has already been taken.' ; } }
在 app/Http/Requests/ProjectRequest.php
檔使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 public function rules ( ) { return [ 'name' => [ 'required' , new Unique ( $this ->user ('api' ), 'projects' ), ], 'private' => 'boolean' , ]; }