email validation not working in update form using laravel validation - laravel

$id = $request->id;
$validation = Validator::make($request->all(), [
'email' => 'unique:customers,email,'.$request->id
]);

You're using a custom validator. You need to handle the validation failure manually. Also your code checks for unique email in the table customers except for the email of the user $request->id. I assume this is intended.
$validator = \Validator::make($request->all(), [
'email' => 'email|unique:customers,email,' . $request->id
]);
if ($validator->fails()) {
// Handle failure
}
The code below will automatically handle validation failure and redirect back with errors and inputs.
$this->validate($request, [
'email' => 'email|unique:customers,email,' . $request->id
]);

You can try something like
Validator::make($data, [
'email' => [
'required',
Rule::unique('customers')->ignore($customer->id),
],
]);

Related

how to edit user email in laravel

i want to edit my user email in laravel, but when i submit the form and then it gives me an error message
The selected Email is invalid.
what do I have to do?
whats wrong with this code?
//in Create Function
'email' => 'required|email|unique:users,email',
//in Update Function is this correct?
'email' => 'required|email|exists:users,email',
Controller
This is my userController for update users
public function update(Request $request, User $user)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string|max:30',
'email' => 'required|email|exists:users,email',
'role' => 'required',
'avatar' => 'required|string|max:150'
],
[],
$this->attributes()
);
if ($validator->fails()) {
$request['role'] = Role::select('id', 'name')->find($request->role);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
}
DB::beginTransaction();
try {
$user->update([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'avatar' => parse_url($request->avatar)['path'],
]);
$user->syncRoles($request->role);
Alert::toast(
__('posts.alert.delete.message.success'),
'success'
);
return redirect()->route('users.index');
} catch (\Throwable $th) {
DB::rollBack();
Alert::toast(
__('posts.alert.delete.message.error', ['error' => $th->getMessage()]),
'errors'
);
return redirect()
->back()
->withInput($request->all())
->withErrors($validator);
} finally {
DB::commit();
}
}
You still want a unique validator, so the user can't update their account to someone else's email address and cause a conflict.
However, to prevent it from failing when the user isn't updating their email address (it would fail the unique validation, because a record already exists with that email - the user's own), you'll want to exempt the user's current record from the validation.
https://laravel.com/docs/9.x/validation#rule-unique
See "Forcing A Unique Rule To Ignore A Given ID":
// at the top of your file
use Illuminate\Validation\Rule;
'email' => [
'required',
'email',
Rule::unique('users')->ignore($user->id),
]
You're validating the request requiring the email to exist in the table :
'email' => 'required|email|exists:users,email',
You need to specify unique in order to check the value is not used in the table (same as creation)
'email' => 'required|email|unique:users,email',
You can't do either
'email' => 'exists:users,email'
or
'email' => 'unique:users,email'
for update function. because if you don't change the email you have to submit the old email to the controller which is not "unique" and if you do change it then it doesn't "exist" in the database.
Instead try it like this:
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user)],
It means the email should be unique unless it is the email from current user.
See the Laravel docs for more information on this:
https://laravel.com/docs/9.x/validation#rule-unique

How can I use fails method validation in controller

controller validator in laravel :
$validationController = $this->validate(request(), [
'title' => 'min:100',
'text' => 'required',
'image' => 'required',
]);
and we can make validator with :
$validationNormaly = Validator::make(request(), [
'title' => 'min:100',
'text' => 'required',
'image' => 'required',
]);
and i can't use $validationController->fails(). how can i use it?
The first validation that you mentioned will fail automatically as designed by the laravel code base.
The Validator::make() i typically use when doing ajax requests and such to the controller method. You will need to run the validation fails method to invoke the failed response like so:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
You Can Use :
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
take advantage of the automatic redirection with error messages

Modify unique attribute validation in Laravel

Trying to customize the error message for unique attribute. Tried changing my validation.php.
$messages = [
'custom' => [
'email' => [
'unique:users' => 'Oops, email is taken. Please try again!'
]
]
],
and I call the validation in controller:
request()->validate([
'email' => 'unique:users',
'password' => 'required|min:3',
]);
And I still get this:
The email has already been taken.
using custom validator
You can create a custom validator and pass your messages into it
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
For you this would mean
$messages = [
'email' => [
'unique' => 'Oops, email is taken. Please try again!'
]
];
$rules = [
'email' => 'unique:users',
'password' => 'required|min:3',
];
$validator = Validator::make(request()->all(), $rules, $messages);
if ($validator->fails()) {
return redirect('route/when/failed')
->withErrors($validator)
->withInput();
}
using language file
In resources/lang/{{language}}/validation.php you can add
'custom' => [
'email' => [
'unique' => 'Oops, email is taken. Please try again!',
],
]

check if validation fails (with custom mesages)

When using the validation like below with custom messages how is possible to check if the validation fails?
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$this->validate($request, $rules, $customMessages);
Like below, without custom messages is possible to use $validator->fails() but in the above case how to verify if the validation fails?
$validator = Validator::make($request->all(), [
//...
]);
if ($validator->fails()) {
//...
}
When you use $this->validate it validate your request against your validation rules and if failed then it redirect to previous page with validation message. If you want to use $validator->fails() then use Validator::make with custom message. Like this
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$validator = Validator::make($request->all(), $rules, $customMessages);
if ($validator->fails()) {
//...
}
Check validator make method https://laravel.com/api/5.0/Illuminate/Validation/Factory.html#method_make
much simpler solution is to use custom handler in app\Exceptions\Handler.php:
public function register()
{
$this->renderable(function (ValidationException $e, $request) {
//list of specific failed tests
$e->validator->failed();
return response()->json(['message' => 'custom message','meow'=>'meow',$e->status);
});
}
this way you keep old behavior AND can still change messages sent back to the user/frontend

Custom Validation Laravel multiple attributes 5.5

In my form I have 2 attributes that need to be unique, I am trying to use Laravels Validator to do this but am very stuck..
Even if i add a return false/true to the function, there are no errors generated and the controller continues on. Am I missing something (not according to their docs :| )
$validator = Validator::make($request->all(), [
'organisationid' => 'required',
'membershipcode' => 'required'
]);
$validator->sometimes('membershipcode', 'required', function($input) {
return false;
});
In the store method in your controller, you can add validation like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique',
'description' => 'required',
]);
$movie = Model::create($request->all());
return redirect('view')->with('message', 'Added successfully');
}
The available validation rules are here: https://laravel.com/docs/5.5/validation#available-validation-rules

Resources