【问题标题】:Laravel: Validation unique on update still failing all the timeLaravel:更新时唯一的验证仍然失败
【发布时间】:2019-12-19 21:51:48
【问题描述】:

我有一个更新表单,其中包含要更新的图像和其他数据不幸的是,它在发布新记录时工作正常,name 字段是唯一字段;我检查了 github 和 stackoverflow 上的所有线程,但没有用,尽管我在 laravel 5.5 中有相同的项目,它工作正常,现在我被 laravel 6 困住了

这是我的表格

let data = new FormData();
data.append('name', this.channel.name);
data.append('base_color', this.channel.baseColor);
data.append('complementary_color', this.channel.complementaryColor);
if (this.file){
  data.append('avatar', this.file);
}

data.append('_method', 'PUT');

axios.post(`/dashboard/channels/${this.channel.name}`, data).then(resp => {
  this.$parent.$emit('channel_updated', resp.data);
}).catch(error => {
  flash(error.response.data, 'danger', 'backEndStyle');
});

这是我的路线

Route::resource('/dashboard/channels', 'ChannelController');

这是我的表单请求

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ChannelRequest 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 [
        'name' => 'required|unique:channels,name,'. $this->id,
        'base_color' => 'required',
        'complementary_color' => 'required',
    ];
}
}

这是我的更新方法控制器

public function update(Channel $channel, ChannelRequest $request)
{
    $channel->update([
        'name' => $request->name,
        'bg_base_color' => $request->base_color,
        'bg_complementary_color' => $request->complementary_color,
    ]);

    return response($channel->fresh(), 200);
}

【问题讨论】:

  • 如果路由参数命名为channel,为什么要使用id?除非另有说明,否则它将基于“id”列忽略
  • 即使我使用 'name' => 'required|unique:channels,name,'。 $this->name, 或 'name' => 'required|unique:channels,name,'。 $this->channel->name,仍然失败
  • 你的意思是$this-&gt;route('channel')-&gt;id?就像在模型的“id”中一样,因为这是规则设置忽略的内容,id 字段,如果没有另行通知?

标签: php laravel vue.js laravel-5


【解决方案1】:

在验证唯一性时使用ignore 约束忽略当前模型

public function rules()
{
    return [
        'name' => ['required', Rule::unique('channels')->ignore($this->route('channel'))],
        'base_color' => 'required',
        'complementary_color' => 'required',
    ];
}

【讨论】:

  • 如果您觉得可以改进答案,总有一个编辑按钮
  • 我不会改变人们的意图,我只是希望有适合 OP 的答案
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 2020-03-30
  • 2014-06-28
  • 1970-01-01
  • 2014-08-20
  • 2018-07-17
  • 2018-08-09
  • 1970-01-01
相关资源
最近更新 更多