I need to update an email with a unique role in the Form Request Validation. I have no problem with creating the user, but the problem is when I try to update the email, it shows that the email is already taken. how can I do something like if the email that is in the input value is owned by the user it can be skipped by the unique role.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
public function rules()
{
return [
'email' => ['sometimes', 'required','email:rfc,dns', 'unique:users,email', 'max:255'],
in controller
public function update(UsersRequest $request, $id)
{
$user = User::find($id);
$user->email = $request->input('email');
$user->save();}
blade code
<input name="email" type="email"
<input name="email" type="email" class="form-control @error('email') is-invalid @enderror" value="{{ $user->email }}" required>
CodePudding user response:
You are in the update method. so obviously you have a user id that is going to be updated so just fetch the user first,
$user = User::findOrFail($id);
Now the validation will be,
'email' => ['sometimes', 'required','email:rfc,dns', ($request->email === $user->email) ? '' : 'unique:users,email', 'max:255'],
Let me know its solves your issue or not.
CodePudding user response:
This is what i prefer
First, your update route must have a {user}
as parameter
Route::put('/users/{user}', ...);
You can also use in your request file
$unique_email = 'unique:users,email';
if ($user = $this->route('user')) {
$unique_email .= ',' . $user->id;
}
// And then add it to rule
return [
'email' => ['sometimes', 'required', $unique_email],
];
CodePudding user response:
Try this
public function rules()
{
switch ($this->method()) {
case 'POST':
{
return [
'email' => 'required|email|max:199|unique:users,email',
];
}
case 'PUT':
case 'PATCH':
{
return [
'email' => 'required|email|unique:users,email,' . $this->user->id,
];
}
default:
break;
}
}
}