我的模型有以下更新功能:
public function update(PartnerRequest $request, $id)
{
$partner = Partner::findOrFail($id);
if(!$partner -> update($request->all())) {
throw new HttpException(500);
}
return response()->json([
'status' => 'ok'
], 201);
}
这是请求文件:
namespace App\Api\V1\Requests;
use Config;
use Dingo\Api\Http\FormRequest;
class PartnerRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required|unique:partners,' . $this->id . ',id',
'email' => 'email'
];
}
public function authorize()
{
return true;
}
}
如果我删除规则上的例外并将其设为'name' => 'required|unique:partners'
,则在输入重复时会出现以下错误消息:
{
"error": {
"message": "422 Unprocessable Entity",
"errors": {
"name": [
"The name has already been taken."
]
},
"status_code": 422
}
}
但问题在于Patch,我无法更新模型(由于唯一的名称规则)。所以,我需要例外。但是,如果我包含它,而不是上面的特定错误,我有一个像这样的通用:
"error": {
"message": "SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: partners.name (SQL: update \"partners\" set \"name\" = test, \"updated_at\" = 2017-03-03 10:47:53 where \"id\" = 3)",
"code": "23000",
"status_code": 500
}
}
路线:
$api->post('partner/store', 'App\\Api\\V1\\Controllers\\PartnerController@store');
$api->get('partner/all', 'App\\Api\\V1\\Controllers\\PartnerController@index');
$api->get('partner/{id}', 'App\\Api\\V1\\Controllers\\PartnerController@show');
$api->patch('partner/{id}', 'App\\Api\\V1\\Controllers\\PartnerController@update');
答案 0 :(得分:0)
你可以尝试做类似的事情:
public function rules()
{
switch ($this->method()) {
case 'POST':
return [
'name' => 'required|unique:partners',
'email' => 'email'
];
case 'PUT':
case 'PATCH':
return [
'name' => 'required|unique:partners,name,' . $this->route('id') . ',id',
'email' => 'email'
];
}
}
希望这有帮助!