无法使用条件验证规则 - Laravel

时间:2020-12-23 19:40:33

标签: php laravel laravel-8 laravel-livewire

我直接绑定到模型属性。我无法提交表单,因为单个 livewire 组件中有两个表单。第一种是编辑用户,由nameemailrole组成,第二种是邀请用户,由email组成。

我无法提交表格,因为我已在受保护财产规则下对这两种表格的规则进行了说明。因此,当我尝试使用第一个表单编辑用户时,它还会检查 email 字段,该字段存在于邀请表单中。我怎样才能让它在这种结构中工作。

  • App\Http\Livewire\UserController.php
public $showUserManagementModal = false;
public $showUserInvitationModal = false;

public User $user;
public Invitation $invitation;

protected function rules() {
    if ($showUserManagementModal = true)
        return [
            'user.name' => 'required | string | max:255',
            'user.email' => 'required | string | email | max:255',
            'role' => 'required',
        ];

    if ($showUserInvitationModal = true)
        return [
            'invitation.email' => 'required | string | email | max:255 | unique:invitations,email',
        ];
}

public function createInvitation() {
    $this -> useCachedRows();

    $this -> resetValidation();
    $this -> invitation = new Invitation();
    $this -> showUserInvitationModal = true;
}

public function saveInvitation() {
    $this -> validate();
    $this -> invitation -> generateInvitationToken();
    $this -> invitation -> save();
    $this -> showUserInvitationModal = false;
}

public function manageUser(User $user) {
    $this -> useCachedRows();

    $this -> resetValidation();
    $this -> user = $user;
    $this -> role = $user -> roles -> pluck('id');
    $this -> showUserManagementModal = true;
}

public function saveUser() {
    $this -> validate();
    $this -> validate([
        'user.email' => 'unique:users,email,'.$this -> user -> id,
    ]);
    $this -> user -> roles() -> sync($this -> role);
    $this -> user -> save();
    $this -> showUserManagementModal = false;

    $this -> dispatchBrowserEvent('notify', $this -> user -> name.' Updated Successfully');
}

1 个答案:

答案 0 :(得分:2)

您的 rules() 方法有两个问题 - 一个是您正在检查局部变量(它不检查类的属性),其次是您为变量赋值而不是比较(单 = 而不是双 ==)。

protected function rules() {
    if ($this->showUserManagementModal === true)
        return [
            'user.name' => 'required|string|max:255',
            'user.email' => 'required|string|email|max:255',
            'role' => 'required',
        ];

    if ($this->showUserInvitationModal === true)
        return [
            'invitation.email' => 'required|string|email|max:255|unique:invitations,email',
        ];
}

您还应该将电子邮件的唯一检查移至 rules() 方法,而不是在 saveUser() 方法中明确检查。

protected function rules() {
    if ($this->showUserManagementModal === true)
        return [
            'user.name' => 'required|string|max:255',
            'user.email' => 'required|string|email|max:255|unique:users,email'.($this->user->id ? ','.$this->user->id : ''),
            'role' => 'required',
        ];

    if ($this->showUserInvitationModal === true)
        return [
            'invitation.email' => 'required|string|email|max:255|unique:invitations,email',
        ];
}