所以我正在尝试为内部项目开发一个 rest API,我遇到了一个问题,当表单请求验证失败时,它会显示 the @index response。
所以我有两条路线;
Route::get('/api/clients', 'ClientController@index');
Route::post('/api/clients', 'ClientController@store');
@index
列出所有客户端,@store
创建一个新客户端,我在@store
方法上有一个表单请求验证器,它检查为客户端提供的名称。
我想要的是当验证器失败时,它会显示带有验证错误的 JSON 响应。但我认为它发生的是验证失败,因此它重定向回到同一页面,但重定向是GET
而不是POST
,因此它列出了所有客户端。
我知道你可以设置你的标题,使它看起来像一个 ajax 请求,它将正确显示 JSON 响应,但我希望它显示 JSON 响应,无论它是否是 ajax。
我已经尝试覆盖我的验证器中的response
方法,该方法不起作用,我已经尝试在验证器中设置wantsJson
方法以返回 true,这再次无效。
非常感谢帮助。
代码如下......
web.php
Route::get('/api/clients', 'ClientController@index');
Route::get('/api/clients/{client}', 'ClientController@show');
Route::post('/api/clients', 'ClientController@store');
Route::put('/api/clients/{id}', 'ClientController@update');
Route::delete('/api/clients/{id}', 'ClientController@delete');
ClientController.php
namespace App\Http\Controllers;
use App\Client;
use App\Http\Requests\ClientRequest;
class ClientController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(ClientRequest $request)
{
return Client::create([
'title' => request('title'),
'user_id' => auth()->id()
]);
}
ClientRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ClientRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required'
];
}
/**
* Get the failed validation response for the request.
*
* @param array $errors
* @return JsonResponse
*/
public function response(array $errors)
{
dd('exit'); // Doesn't work
}
}
5 回答
你可以这样试试
请在表单请求中首先使用以下内容
然后
现在,如果您尝试验证,那么它将返回
在发出请求时,我们应该发送标题信息。
就是这样,现在 laravel 不会重定向并将错误消息作为 JSON 发送。
试试这个
打开 app/Exceptions/Handler.php 文件
包括使用
然后添加方法
现在您可以像 ajax 请求那样获得标准的 validationFailure 响应
我刚刚创建了一个
ApiFormRequest
覆盖FormRequest::failedValidation方法,如下所示:然后你就像这样使用
验证失败's(in 控制器时,有一种方法可以简单地返回错误。例:
方便,干净