我想创建一个自定义的PUT路由来管理AJAX请求
Route::post('some/{id}/another/new', 'SomeController@store');
Route::put('some/{cid}/another/{id}/edit', 'SomeController@update');
并且我想使用FormRequest
作为请求参数
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(DirectionRequest $request)
{
$data = $request->validated();
$direction = Direction::create($data);
return response()->json($direction, 201);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Direction $direction
* @return \Illuminate\Http\Response
*/
public function update(DirectionRequest $request, $clientId, $directionId )
{
$data = $request->validated();
$direction = Direction::find($directionId);
$direction->update($data);
return response()->json($direction, 201);
}
DirectionRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class DirectionRequest 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 [
'country' => 'required|string|max:255'
];
}
/**
*
* @return type
*/
public function all($keys = null) {
$data = parent::all();
$data['created_by'] = Auth::User()->id;
return $data;
}
/**
*
* @param Validator $validator
* @throws HttpResponseException
*/
protected function failedValidation(Validator $validator) {
throw new HttpResponseException(response()->json($validator->errors(), 422));
}
}
和AJAX调用
const editData = new FormData();
editData.append("country", document.getElementById('country').value);
return fetch(`/some/` + sidId + `/another/` + id + `/edit`, {
method: "PUT",
body: editData,
headers: new Headers({
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
})
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
console.log(error)
});
我收到422 Unprocessible Entity
错误,该错误返回我所有带有错误的模型字段,但它们由AJAX请求填充并发送。
如何在自定义路由中使用FormRequest来使用验证规则?我不想复制带有规则的代码,因为我在另一个方法(存储)中使用了FormRequest,并且可以正常工作
简单的Request
显示看跌数据,但FormRequest
不显示