假設我有一個用于驗證FormRequest欄位唯一性的自定義邏輯,需要在資料庫中找到另一個資源,如下所示:
class CreateMyResourceRequest extends FormRequest {
public function rules() {
return [
'my_field' => [
Rule::unique('some_other_resource', 'some_column')
->where(function ($query) {
$otherResource = SomeOtherResource::where(...)->firstOrFail();
// Process the retrieved resource
}),
]
該firstOrFail()呼叫顯然使請求失敗并出現 404 - 未找到,而我想回傳 422 并在該欄位上出現驗證錯誤。
有沒有辦法在使用Rule::unique()框架提供的同時實作這一點?
提前致謝!
uj5u.com熱心網友回復:
我建議以下
public function rules()
{
return [
"your_field" => ["you_can_have_more_validations_here", function($key, $value, $cb) {
$queryResult = SomeModel::find(1);
if (someCondition) {
$cb("your fail message");
}
}]
];
}
運行時$cb驗證將失敗并顯示 422
uj5u.com熱心網友回復:
不要使用firstOrFail,而只是使用first并檢查輸出是否為空。如果是,則回傳 false。
或者,更多的 Laravel 方法是:
$query->leftJoin('otherresource', 'primarykey', 'foreignkey')->where(...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/430341.html
標籤:php 拉拉维尔 laravel-8 laravel 表单请求
