Unique field validation issue in laravel - php

I'm trying to validate a unique entry in my laravel app
following is my validation array,
$website = $websiteModel->find($id);
$this->validate($request, [
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
], $request->all());
My validation working properly BUT,
When i tried to enter a duplicate value for my domain field, It get validated properly but not showing the error message, saying sorry the name is already exists...
<input type="text" id="domain" class="form-control" name="domain" >
{!! $errors->first('domain', '<span class="help-block" role="alert">:message</span>') !!}
Here in this span it shows nothing but in the common error message area it shows sorry the form cannot be updated... So how can I validate the field properly and display the relevant error message

Do something like this:
On insert request use
'domain' => [
...
'unique:websites,domain'
]
On update request use
'domain' => [
...
"unique:websites,domain,{$this->website->id}"
]
Or
'domain' => [
...
Rule::unique('websites', 'domain')->ignore($this->website)
]

You passed $request->all() as validation messages.
Please Try:
$website = $websiteModel->find($id);
$request->validate([
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
]);

don't you need to pass duplicate column in ignore Rule To instruct the validator to ignore the website domain, except for it self ? for example like
Rule::unique('apps')->ignore($website->id)

please try this one . it helps to solve your problem
use exception and validator in top of the file
use Exception;
use Validator;
$rules = [
'subDomainName' => 'required|unique:sub_domain_name',
];
$validator = Validator::make($request->all(), $rules, $message);
if ($validator->fails()) {
throw new Exception(implode('\n', $validator->errors()->all()));
}
sub_domain_name : this is database column name

Related

Laravel update only the changed field attribute(s)

I'm trying to run this update function in my laravel controller. Here my domain name is an unique attribute.
The problem
But now every time when I'm trying to update any field rather than domain name field, it showing me an error saying domain name is already existing. So how can I update only the fields which have been changed? what changes do I need to be made in the following function.
public function update(Request $request,Website $app, $id)
{
$this->validate($request, [
'subDomainName' => ['required'],
'subDomainSuffix' =>['required'],
'packageType'=>['required'],
'themeid'=>['required'],
'lang'=>['required'],
'user'=>['required'],
'domain' => ['required', 'string','min:2', 'max:255','unique:apps'],
],$request->all());
$fullDomain = $request->domain;
$app->domain=$fullDomain;
Website::find($id)->update($request->all());
return redirect()->route('customers.index')
->with('success','Website updated successfully');
}
You can specify a model to be ignored on the unique attribute:
public function update(Request $request, Website $websiteModel, int $id)
{
$website = $websiteModel->find($id);
$this->validate($request, [
'subDomainName' => ['required'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
], $request->all());
$website->update($request->all());
return redirect()
->route('customers.index')
->with('success','Website updated successfully');
}
Don't forget to import Rule: use Illuminate\Validation\Rule;

Laravel 6 validation: there is limit in number of rules?

I am using Laravel 6.13.1.
I have the following validation
$validator = Validator::make($request->all(), [
'name' => 'required|max:100',
'email' => 'required|email',
'mobile_number' => 'required',
'date_of_birth' => 'required',
'address' => 'required',
'category' => 'required',
'other_category' => 'required_if:category,==,Others',
'sub_caste' => 'required',
'photo' => 'required',
'status' => 'required|integer',
'father_name' => 'required',
'father_occupation' => 'required',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
It has 12 rules and it works. If I add one more rule then the validator stops working.
{{$errors}} gives an empty array in the view file.
Edit 1: The validation with 12 rules shows all error messages, but if I add one more validation like
$validator = Validator::make($request->all(), [
'name' => 'required|max:100',
'email' => 'required|email',
'mobile_number' => 'required',
'date_of_birth' => 'required',
'address' => 'required',
'category' => 'required',
'other_category' => 'required_if:category,==,Others',
'sub_caste' => 'required',
'photo' => 'required',
'status' => 'required|integer',
'father_name' => 'required',
'father_occupation' => 'required',
'mother_name' => 'required',
]);
then no error messages. {{$errors}} is an empty array.
In my view, I am using the following code to list errors
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Edit 2: I tried the same validation on Laravel 5.5 and it works well as indented.
I was facing the same problem, and found somewhere that maybe this is caused by the size of error messages. I've changed the SESSION_DRIVER env option from "cookie" to "file" and it worked!
I don't think that it has a limit, However you can create a request and put all your validation on it like that:
php artisan make:request UserRequest
You can check out this link Form Request Validation

Laravel validation username must not start with specific string

I want to register user but I want to put validation rule on username that username should not start with special characters and also should not start with web. I found regex that work fine special characters but detect the string it give me error of Invalid format
return [
'username' => [
'required',
'regex:/^\S*$/u',
'regex:/^[_]?[a-zA-Z0-9]+([_.-]?[a-zA-Z0-9])*$/',
'unique:users'
],
'full_name' => 'required',
];
Try this?
return [
'username' => [
'required|
not_regex:/^[web_-][a-z_\-0-9]*/i|
regex:/^[A-Za-z_ \-0-9]+$/u|
unique:users'
],
'full_name' => 'required',
];
This should work as you want it to
return [
'username' => [
'required',
'regex:/^(?!web)[a-zA-Z]\w+$/',
'unique:users'
],
'full_name' => 'required',
];
Here's a regex101 demo for you to test it out.

laravel 5.2 Method [validate1] does not exist

My validation fails with this:
$this->validate($request, [
'name' => ['required'],
'email' => ['required', 'email', 'unique:organisers',$organiser->id,'organisers_id'],
'organiser_logo' => ['mimes:jpeg,jpg,png', 'max:10000'],
]);
but it works with this:
$this->validate($request, [
'name' => ['required'],
'email' => ['required', 'email', 'unique:organisers'],
'organiser_logo' => ['mimes:jpeg,jpg,png', 'max:10000'],
]);
This:
'unique:organisers',$organiser->id,'organisers_id'
needs to be:
'unique:organisers,'.$organiser->id.',organisers_id'
or (note the double-quotes):
"unique:organisers,{$organiser->id},organisers_id"
The , means "new array element", the . means "add to this string".

Laravel 5.4 sometimes|required validation not raising on "null" input

I'm having a problem validating inputs that are only going to be present sometimes in the Request.
// Controller
public function update(Request $request, User $user)
{
$updateResult = $user->updateUser($request);
return dd($updateResult);
}
// User Model
protected $validation = [
'rules' => [
'email' => [
'sometimes',
'email',
'required',
],
'password' => [
'sometimes',
'min:6',
'required',
],
'first_name' => [
'sometimes',
'required',
],
'last_name' => [
'sometimes',
'required',
],
],
'messages' => [
'email.required' => 'An email is required.',
'email.email' => 'The email must be valid.',
'password.required' => 'A password is required.',
'password.min' => 'Your password must be at least six (6) characters long.',
'first_name.required' => 'Your first name is required.',
'last_name.required' => 'Your last name is required.',
],
];
public function updateUser(Request $request)
{
$validation = Validator::make($request->all(), [
$this->validation['rules'],
$this->validation['messages'],
]);
if ($validation->fails())
{
return $validation;
}
else
{
return "OK";
}
}
So in some update pages $request->all() is only going to have a subset of these fields. However, even a field is present, but the value is null, the required doesn't trigger.
[
'first_name' => null,
'last_name' => 'Davidson',
'job_title' => 'Tech Support',
]
The above request array will return "OK"... If I remove sometimes from the fields, then when a partial input request is sent, it fails saying the fields are required.
I am clearing missing something here, but from reading the docs I thought I'd configured this correctly:
In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email', ]);
The problem you are facing is simply due to an error in your call to the validator. The second parameter is not a multidimensional array as you passed. The rules array and the messages array are separate parameters.
$validation = Validator::make($request->all(), [
$this->validation['rules'],
$this->validation['messages'],
]);
Should be replaced by
$validation = Validator::make($request->all(),
$this->validation['rules'], $this->validation['messages']);
In Laravel 5.4 empty strings are converted to Null by the ConvertEmptyStringsToNull middleware... that might cause you some issues...
You should add nullable to all your optional validations...
Hope this helps
'first_name' => [
'sometimes',
'required',
],
Will never work as expected. Sometimes indicates: if something comes, what is the next rule? In this case 'required'. Required what? Change this to:
'first_name' => [
'sometimes',
'required',
'min:1',
],
The null value will still be a null value if no input is given and won't fail. If you want to keep the value of the field in the table for updates, populate the input in the form with it's respected values.
The null value was send as '' and got nulled by the ConvertEmptyStringsToNull::class in the app\Http\kernel.php middleware.

Categories