Here is my code
$arParams = $request->all();
$validator = Validation::createValidator();
$groups = new GroupSequence(['Default', 'custom']);
$constraint = new Assert\Collection([
'name' => new Assert\Length(['min' => 2]),
'city' => new Assert\Length(['min' => 2]),
'email' => new Assert\Email(),
'phone' => new Assert\Length(['min' => 18]),
'message' => new Assert\NotNull()
]);
$violations = $validator->validate($arParams, $constraint, $groups);
If i get some errors, how can I get an array like
['name' => not enough symbols, 'email' => wrong email]?
I tried to use foreach on $violations but cant find all the methods of its elements Phpstorm sign $violation as mixed. I found only $violation->getMessage() and ->getCode()
I recommend you to read this article https://symfony.com/doc/current/validation.html
If validation fails, a non-empty list of errors (class ConstraintViolationList) is returned.
So you can get your list this way:
if ($violations->count() > 0) {
$formatedViolationList = [];
for ($i = 0; $i < $violations->count(); $i++) {
$violation = $violations->get($i);
$formatedViolationList[] = array($violation->getPropertyPath() => $violation->getMessage());
}
}
Couple explanations. We use methods from violation api count() or get a number of violations, and after in for loop we use get($i) for get every violation by index. After we use getPropertyPath() for get path (name of your property) and getMessage() for get message.
Related
A newbie here in terms of Laravel validation - I've searched and checked the manual but can't seem to find an answer to this. I'm using Laravel 8.0.
As per the Laravel manual I have created a manual validation to validate my array, it contains data similar to the below:
$row = array('John','Doe','john.doe#acme.com','Manager');
Because the array has no keys, I can't work out how to reference the array items using their index when creating the Validator, I've tried this:
$validatedRow = Validator::make($row, ['0' => 'required|max:2', '1' => 'required']);
$validatedRow = Validator::make($row, [0 => 'required|max:2', 1 => 'required']);
$validatedRow = Validator::make($row, [$row[0] => 'required|max:2', $row[0] => 'required']);
But no luck - does anyone have any suggestions?
Use Validator
use Illuminate\Support\Facades\Validator;
Then Update your code
$row = array('John','Doe','john.doe#acme.com','Manager');
$rule = [
'0' => 'required|string',
'1' => 'required',
'2' => 'required|email',
'3' => 'required'
];
$validator = Validator::make($row, $rule);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()->all()], 422);
}else{
echo 'ok';
}
Currently I have set of array.
and
I can easily insert these data to my database using Laravel without doing any validations
here's the sample array
CODE:
$excel1 = Importer::make('Excel');
$excel1->hasHeader(true);
$excel1->load($savePath.$fileName);
$excel1->setSheet(2);
$collection1 = $excel1->getCollection();
$arr1 = json_decode($collection1,true);
foreach ($arr1 as $row1) {
$insert_data1[] = array(
'projCode' => $projCode,
'emp_id' => $row1['company_id'],
'type' => 'EMP',
'deleted' => 0,
'by_id' => auth()->user()->id,
'updated_by' => auth()->user()->name,
'created_at' => now(),
'updated_at' => now(),
);
}
dd($insert_data1);
OUTPUT:
and I'm using this code to insert these data to my table
DB::table('tbl_emp_proj')->insert($insert_data1);
and this works fine but the problem is,
I'm trying to validate if emp_id exists or not in my users table
Here's my users table
The value of emp_id from array should check if it already exists in my users using company_id field from users. How can I validate it if $insert_data1 is an array and should be check if it exists on database?
UPDATE
currently i have this validator and I tried to add up the $Insert_data1 but gives me undefined var for $insert_data1.
$validator = Validator::make(
[
'file' => $request->file,
'extension' => strtolower($request->file->getClientOriginalExtension()),
],
[
'file' => 'required|max:5000',
'extension' => 'required|in:,csv,xlsx,xls',
],
$insert_data1,
[
'*.emp_id' => "required|exists:users,company_id",
]
);
You can use Laravel Validator to validate any arrays as if its a request input.
use Illuminate\Support\Facades\Validator;
$validator = Validator::make(
$insert_data1,
[
'*.emp_id' => "required|integer|exists:users,company_id",
]
);
EDIT:
You can receive error messages and error items with the validator APIs.
$failed = $validator->fails(); //boolean
$errors = $validator->errors();
$validated = $validator->validated();
$invalid = $validator->invalid();
I have a Podio app which is populated by the php API via a form on a website.
Using the Create Item snippet works for text fields, currency values, etc but have been I unable to untangle the documentation as to how to set a category field.
The category field, "attending", is a simple yes/no choice.
The method shown here generates a server error when combined with Create Item snippet as below:
$fields = new PodioItemFieldCollection(array(
new PodioTextItemField(array("external_id" => "title", "values" => $name)),
new PodioTextItemField(array("external_id" => "email", "values" => $email)),
));
$item = new PodioItem(array(
'app' => new PodioApp(intval($app_id)),
'fields' => $fields,
));
pseudo code: if attending = yes, $attending = 1, else $attending = 2 //id's of yes and no in category field
$item->fields['attending']->values = $attending;
$item->save();
What am I missing? Thanks.
For those still searching for an answer: The trick is to use an array.
Perform the evaluation of $attending before opening the Collection and then simply
add this line into the PodioItemFieldCollection.
new PodioCategoryItemField(array(
'external_id' => 'attending', 'values' => array($attending))),
So the whole snippet would look like this
($foo == 'yes') ? $attending = 1: $attending = 2 ; // evaluating $foo for yes
$fields = new PodioItemFieldCollection(array(
new PodioTextItemField(array("external_id" => "title", "values" => $name)),
new PodioTextItemField(array("external_id" => "email", "values" => $email)),
new PodioCategoryItemField(array(
'external_id' => 'attending', 'values' => array($attending))) // must be an array
));
$item = new PodioItem(array(
'app' => new PodioApp(intval($app_id)),
'fields' => $fields,
));
$item->save();
You can find examples at: http://podio.github.io/podio-php/fields/#category-field
If it's still not working, place podio-php into debug mode so you can see what data is being sent to Podio: http://podio.github.io/podio-php/debug/
Here is my Rule :
Table Name is : company_info
I have only two fields CompanyID and Telephone
In the update section, i want to check whether the Telephone Number exists for other columns and if the own field have it i don't want to check it. (Currently it checks the own data and returning with Telephone number was taken already).
'Telephone' => 'unique:company_info',
Then i tried with the below rule
But i miss in the
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$Telephone)
Here is my Code :
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$rule = array(
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid
)
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return "0"."||".$messages = $validator->messages()->first('Telephone');
}
While the update query i need to check for the unique rule except the given id
I refered this one http://laravel.com/docs/4.2/validation#rule-unique
But i am not getting return on $validator = Validator::make($data,$rule);
How can i check for the unique value except the own column
I believe you have the wrong syntax for unique validation
it should be
'Telephone' => 'unique:company_info,CompanyID,'.$companyid
or
'Telephone' => 'required|unique:company_info,CompanyID,'.$companyid
and not
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid
Can try this as the Laravel Validation provides us various features
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$data = array('companyid'=>$companyid, 'Telephone'=>$Telephone );
//FOR INSERTING NEW DATA
$rule = array(
'Telephone' => 'required|unique:company_info,Telephone,{:id}'
);
$validator = Validator::make($data,$rule);
//FOR UPDATING AN EXISTING DATA
public static function rule ($id, $merge=[]) {
return array_merge(
[
'Telephone' => 'required|unique:company_info,Telephone,'.$id,
],
$merge);
}
$validator = Validator::make($data,self::rule($id));
Comment for errors...
Try following code
'Telephone' => 'unique:company_info,Telephone,'.$companyid.', CompanyID';
{rule} =>
'unique:{table_name},{unique_column_name},{except_column_value},{except_column_name}'
I'm trying to validate this input:
$values = [
'id' => $input['id'][$i],
'template_id' => $input['template_id'][$i],
'schedulable_id' => $id,
'schedulable_type' => $type,
'order_by' => $i
];
Against these rules found in my Schedule class:
public static $rules = [
'template_id' => 'required|integer|exists:templates,id',
'schedulable_id' => 'required|integer',
'schedulable_type' => 'required|in:Item,Order',
'order_by' => 'integer'
];
When I do the following, I always get an array to string conversion error in "/laravel/vendor/laravel/framework/src/Illuminate/Validation/Validator.php" on line 905:
$validator = Validator::make($values, Schedule::$rules);
if ($validator->fails()) {
$errors[$i] = $validator->messages();
continue;
}
Why would this be happening?
Just discovered I had Ardent's $forceEntityHydrationFromInput = true and my input cannot be pulled directly from Input for validation purposes due to the fact that it is submitted as an array of partially referenced values.
To fix this, change to $forceEntityHydrationFromInput = false and use standard input validation procedure instead of relying on Ardent's magic.
Sometimes clever packages are too clever.