Laravel更新模型,具有属性的唯一验证规则

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel更新模型,具有属性的唯一验证规则相关的知识,希望对你有一定的参考价值。

我有一个laravel User模型,它对usernameemail有一个独特的验证规则。在我的存储库中,当我更新模型时,我重新验证字段,以便不会出现所需规则验证的问题:

public function update($id, $data) {
    $user = $this->findById($id);
    $user->fill($data);
    $this->validate($user->toArray());
    $user->save();
    return $user;
}

这在测试中失败了

ValidationException: {"username":["The username has already been taken."],"email":["The email has already been taken."]}

有没有办法优雅地解决这个问题?

答案
public static function custom_validation()
{
    $rules = array('title' => 'required ','description'  => 'required','status' => 'required',);
    $messages = array('title.required' => 'The Title must be required','status.required' => 'The Status must be required','description.required' => 'The Description must be required',);
    $validation = Validator::make(Input::all(), $rules, $messages);
    return $validation;
}
另一答案

我有同样的问题。我做了什么:添加我的视图隐藏字段与模型的ID和验证器检查唯一,只有我从视图中获得一些ID。

$this->validate(
        $request,
        [
            'index'       => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
            'name'        => 'required',
            'surname'     => 'required',
        ]
);
另一答案
'email' => [
    'required',
    Rule::exists('staff')->where(function ($query) {
        $query->where('account_id', 1);
    }),
],

'email' => [
    'required',
    Rule::unique('users')->ignore($user->id)->where(function ($query) {
        $query->where('account_id', 1);
    })
],
另一答案

您可以尝试下面的代码

return [
    'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
    'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
    'password' => 'required|min:6',
    'confirm-password' => 'required|same:password',
];
另一答案

如果您有另一列用作外键或索引,那么您必须在此规则中指定该列。

'phone' => [
                "required",
                "phone",
                Rule::unique('shops')->ignore($shopId, 'id')->where(function ($query) {
                    $query->where('user_id', Auth::id());
                }),
            ],
另一答案

对于自定义FormRequest和Laravel 5.7+,您可以获得更新模型的ID,如下所示:

public function rules()
    {
        return [
            'name' => 'required|min:5|max:255|unique:schools,name,'.Request::instance()->id
        ];
    }
另一答案

角色更新的简单示例


// model/User.php
class User extends Eloquent
{

    public static function rolesUpdate($id)
    {
        return array(
            'username'              => 'required|alpha_dash|unique:users,username,' . $id,
            'email'                 => 'required|email|unique:users,email,'. $id,
            'password'              => 'between:4,11',
        );
    }
}       

.

// controllers/UsersControllers.php
class UsersController extends Controller
{

    public function update($id)
    {
        $user = User::find($id);
        $validation = Validator::make($input, User::rolesUpdate($user->id));

        if ($validation->passes())
        {
            $user->update($input);

            return Redirect::route('admin.user.show', $id);
        }

        return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
    }

}
另一答案

或者您在表格申请中可以做的是(对于Laravel 5.3+)

public function rules()
    {
        return [

            'email' => 'required|email|unique:users,email,'.$this->user, //here user is users/{user} from resource's route url
               ];
    }

我已经在Laravel 5.6中完成了它并且它起作用了。

另一答案

我正在为Store和Update调用不同的验证类。在我的情况下,我不想更新每个字段,所以我有创建和编辑的公共字段的baseRules。为每个添加额外的验证类。我希望我的例子很有帮助。我正在使用Laravel 4。

模型:

public static $baseRules = array(
    'first_name' => 'required',
    'last_name'  => 'required',
    'description' => 'required',
    'description2' => 'required',
    'phone'  => 'required | numeric',
    'video_link'  => 'required | url',
    'video_title'  => 'required | max:87',
    'video_description'  => 'required',
    'sex' => 'in:M,F,B',
    'title'  => 'required'
);

public static function validate($data)
{
    $createRule = static::$baseRules;
    $createRule['email'] = 'required | email | unique:musicians';
    $createRule['band'] = 'required | unique:musicians';
    $createRule['style'] = 'required';
    $createRule['instrument'] = 'required';
    $createRule['myFile'] = 'required | image';

    return Validator::make($data, $createRule);
}

public static function validateUpdate($data, $id)
{
    $updateRule = static::$baseRules;
    $updateRule['email'] = 'required | email | unique:musicians,email,' . $id;
    $updateRule['band'] = 'required | unique:musicians,band,' . $id;
    return Validator::make($data, $updateRule);
}

控制器:存储方法:

public function store()
{
    $myInput = Input::all();
    $validation = Musician::validate($myInput);
    if($validation->fails())
    {
        $key = "errorMusician";
        return Redirect::to('musician/create')
        ->withErrors($validation, 'musicain')
        ->withInput();
    }
}

更新方法:

public function update($id) 
{
    $myInput = Input::all();
    $validation = Musician::validateUpdate($myInput, $id);
    if($validation->fails())
    {
        $key = "error";
        $message = $validation->messages();
        return Redirect::to('musician/' . $id)
        ->withErrors($validation, 'musicain')
        ->withInput();
    }
}

以上是关于Laravel更新模型,具有属性的唯一验证规则的主要内容,如果未能解决你的问题,请参考以下文章

在 laravel 5 中更新具有唯一列的模型

在 laravel 中更新数据时显示错误的唯一键验证

Laravel 唯一的验证规则,除了不工作

Laravel 5.5 对具有不同列名的单独表的唯一验证规则

Laravel 5.4 验证请求,如何处理更新时的唯一验证?

Laravel 检查没有自身更新的唯一规则