Laravel only ignore field if user id is present

Viewed 22

If an user is logged in I need to ignore if the email field already exists in the users table. But if the user is not logged in the rule should be applied.

Naturally I only have the user id if the user is logged in. So what is your alternative to this?

public function rules(): array
{
    return [
        'email' => ['required', 'email:filter', Rule::unique('users')->ignore(Auth::user()->id)],
    ];
}
1 Answers

You can define the rules as a variable, and append the Rule if the Auth::user() is present:

public function rules(): array {
  $rules = [
    'email' => [
      'required',
      'email:filter'
    ]
  ];

  if (Auth::user()) {
    $rules['email'][] = Rule::unique('users')->ignore(Auth::user()->id);
  }

  return $rules;
}

However, I would expect that you still want emails to be unique within the users table of your Database, regardless if a User is logged in or not, in which case you can use a ternary:

public function rules(): array {
  return [
    'email' => [
      'required',
      'email:filter',
      Auth::user() ? Rule::unique('users')->ignore(Auth::user()->id) : Rule::unique('users')
    ]
  ];

Use whatever approach works best for your scenario.

Related