【问题标题】:Custom PUT route with FormRequest in Laravel在 Laravel 中使用 FormRequest 自定义 PUT 路由
【发布时间】:2023-03-16 15:50:01
【问题描述】:

我想创建一个自定义 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 不显示

【问题讨论】:

  • 你能显示console.log(editData);的输出吗?另外,您能否检查浏览器中的网络选项卡以确认请求数据的格式是否正确?
  • 我已经更新了代码块。 Simple Request 显示放置数据,但 FormRequest 不显示。我对POST 方法使用相同的代码,似乎没问题
  • 在这种情况下,您能否添加仅使用Request 时的代码和DirectionRequest 类中的代码?
  • 你可以设置发布的方法,然后在你的表单中做这样的事情:{{ method_field('PUT') }}

标签: laravel validation routes request entity


【解决方案1】:

在关注@RossWilson 链接之后 laracast.com 我已将请求类型更改为 POST,然后我可以使用 FormRequest 规则和其中的其他内容验证输入

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2021-11-16
    • 2018-10-04
    • 2018-09-10
    • 2015-02-03
    • 2015-04-26
    • 2013-09-22
    • 2018-02-18
    相关资源
    最近更新 更多