我没有得到我期望的响应。失败的验证返回默认错误消息,即使提供了自定义消息
这是一个位置的Web服务请求的控制器代码:
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
请求是http://mydomain/index.php/api/v1/location/[email protected]^
响应的原因,我想到的是:{ “结果”:0,“原因“:”Name must be alphanumeric“,”data“:[],”statusCode“:404}
我得到的实际响应是:{”result“:0,”reason“:”给定的数据是无效“,”data“:[],”statusCode“:404}
请帮忙。这正在扰乱我。
这仍然没有解决问题。显然这是其他Laravel开发人员遇到的问题。看看https://github.com/laravel/framework/issues/21059 – user3125602
不,你设置了无效的消息。当你使用'alpha_num'验证规则时,你应该使用'name.alpha_num'来使它工作。所以要么你做错了什么,要么你在你的问题中输入了错误的代码 –
感谢你的回应,Marcin。我做了你推荐的更正。所有功劳都归功于你,你是对的 - 我犯了错误,他们会创造他们自己的问题,但是,我的JSON中无用的响应的根本原因仍然没有解决。我已经发现了更广泛的解决方案,但是我将作为答案发布。 – user3125602