Laravel Request的延伸功能

  1. prepareForValidation

可以在validate規則前,做input value的修改,或建立指定的新欄位

public function prepareForValidation()
{
$this->merge([
'raw_withdraw' => strip_tags($this->withdraw),
'raw_bankbook' => strip_tags($this->bankbook),
'raw_deposit' => strip_tags($this->deposit),
'raw_rule' => strip_tags($this->rule),
'raw_service' => strip_tags($this->service),
]);
}

2. Validator::extend

建立一個驗證規則

use Illuminate\Support\Facades\Validator;

public function __construct()
{
parent::__construct();

/**
* 檢查該級別是否存在任何會員套用
*/
Validator::extend('no_user_using', function ($attribute, $value) {
return !(Member::where('user_level_id', '=', $value)->get()->count() > 0);
});

/**
* 檢查刪除對象不可為預設級別
*/
Validator::extend('check_delete_level', function ($attribute, $value) {
return (MemberLevel::where('id', '=', $value)->first()->name !==
config('platform.admin_console.default_member_level_name'));
});
}
public function rules()
{
return [
'identify' => ['required', 'check_delete_level', 'no_user_using']
];
}

3. attributes

自定義 validation 屬性名稱

public function rules()
{
return [
'identify' => ['required', 'check_delete_level', 'no_user_using']
];
}

public function attributes()
{
return [
'identify' => '識別碼'
];
}

4. messages

自定義 validation 錯誤訊息

public function rules()
{
return [
'identify' => ['required', 'check_delete_level', 'no_user_using']
];
}
public function messages()
{
return [
'no_user_using' => '無任何成員套用',
'check_delete_level' => '刪除預設級別',
];
}

5. Validator::replacer

修改動態填入validation 屬性名稱

Validator::replacer('required_if', function ($message, $attribute, $rule, $parameters) {
$message = str_replace(
':other',
__('validation.attributes.' . $parameters[0]),
$message
);

$message = str_replace(
':value',
__('validation.' . $parameters[1]),
$message
);

return $message;
});