如果您编辑/更新该特定对象,laravel 的唯一名称表示已经使用

问题描述:

我有一个表 Portfolios,我没有在 url 中显示投资组合的 id,而是使用 getRouteKeyName() 显示投资组合的名称.所以我希望名称是唯一的,否则如果它已经存在,它可能会显示错误的投资组合.我为 name 字段设置了唯一的规则.如果我现在编辑/更新投资组合,它会显示:名称已被占用."

I have a table Portfolios and instead of showing the id of the portfolio in the url I show the name of the portfolio with getRouteKeyName(). So I want the name to be unique because else it can show the wrong portfolio if it already exists. I set up the rules for the name field to be unique. If I now edit/update the portfolio it says: "The name is already taken."

我该如何解决这个问题?它需要是唯一的,但如果您在不更改名称的情况下更新该投资组合,就不应该这样说,对吗?

How can I resolve this? It needs to be unique but if you updating that portfolio without changing the name it should't say that, right?

模型组合:

public function getRouteKeyName()
{
    return 'name';
}

作品集请求:

public function rules()
{
    return [
        'name' => 'required|max:30|unique:portfolios',
    ];
}

你必须向规则传递一个额外的属性

You have to pass an extra attribute to rules

public function rules()
{
    return [
        'name' => 'required|max:30|unique:portfolios,name,'.$name.
    ];
}

$name 是要跳过的变量.

希望能帮到你