在 Laravel 5.8 使用 Rule 自訂驗證規則

做法

With

設計一個檢查請求參數是否符合特定關聯的驗證規則,例如可接受 projectsenvironments 參數,則以下請求將通過驗證:

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
{
/**
* @var array
*/
protected $values;

/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($values)
{
$this->values = $values;
}

/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
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;
}

/**
* Get the validation error message.
*
* @return string
*/
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;

/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($user, $table)
{
$this->user = $user;

$this->table = $table;
}

/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$table = $this->table;

if ($this->user->$table()->where($attribute, $value)->first()) {
return false;
}

return true;
}

/**
* Get the validation error message.
*
* @return string
*/
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',
];
}