I tried to put all the validation rules to my database and put it to array
why is not working when you put it in array?
$data = model::where('page','post.create')->get();
foreach($data as $value){
$Rules[] = array($value->post_name => $value->validation);
}
$validator = Validator::make($request->all(), [$Rules]);
Please read the Laravel documentation properly: https://laravel.com/docs/5.6/validation
The mistake is in your 2nd argument in Validator::make, you must pass an array with 'field' => 'validation_rule' pairs. E.g.
[
'title' => 'required|unique:posts|max:255',
'body' => 'required'
]
This code $Rules[] = array($value->post_name => $value->validation); will automatically append numeric array like for example like this:
[
'title' => 'required|unique:posts|max:255'
],
[
'body' => 'required'
]
And this is not what you want. You may also try to learn debugging my friend. Try to check the value of $Rules by running dd($Rules);.
So the correct syntax is this:
$data = model::where('page','post.create')->get();
foreach($data as $value){
$Rules[$value->post_name] = $value->validation;
}
$validator = Validator::make($request->all(), $Rules);
$data = model::where('page','post.create')->get();
foreach($data as $value){
$Rules[] = array($value['post_name'] => $value['validation']);
}
$validator = Validator::make($request->all(), $Rules);
I think you should give the variable name inside array in line 3 and for using array $Rules you should not give the name inside square bracquet in line 5.
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';
}
I am new to laravel and working on apis, I have made an api in which i have implemented validation.Everything is working fine but i am stuck on a little thing. I want to to change the key name in the validation error. For example For the "unique" validation error. This is what now showing
I want to rename "email"(text) key with "message"(text)
I have tried so many thing in illuminate/support/validation.php
messagebag.php file but if it changes then error show of "data undefined".
The links i followed are
https://stillat.com/blog/2018/04/21/laravel-5-message-bags-adding-messages-to-the-message-bag-with-add
https://laracasts.com/discuss/channels/laravel/custom-validation-message-for-array-using-different-key?page=0
Override laravel validation message
This is the validation code
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
You can manually loop over the error MessageBag and construct the response to replace a key
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
$errors = [];
foreach ($validator->errors()->messages() as $key => $value) {
if($key == 'email')
$key = 'message';
$errors[$key] = is_array($value) ? implode(',', $value) : $value;
//implode is for when you have multiple errors for a same key
//like email should valid as well as unique
}
$result = array("status" => count($errors)?0:1, 'data'=>$errors);
return $result;
In resources - lang - en (Or Any Langauge) - validation.php
Put This code in bottom:
'attributes' => [
'email' => 'The Email',
],
In order to change the key of the error message of a certain field, you can transfer the validation of this particular field from the request to the controller (or service). This way you can throw an error with any name you want.
For example:
if (#your validation of the field failed#) {
throw ValidationException::withMessages(['your_key' => 'your message']);
}
And don't forget this line:
use Illuminate\Validation\ValidationException;
The error now will look like this:
{
"message": "The given data was invalid.",
"errors": {
"your_key": [
"your message"
]
}
}
if I understand the problem well. This will help you:
a https://laravel.com/docs/7.x/validation#rule-unique
In your case:
'email' => 'required|email|unique:users,message'
unique:table,column,except,idColumn
Hope it helps.
In Laravel, you can try and validate your email this way:
'email'=>'required|email'
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();
How can I perform validation on custom array in Lumen framework. e.g:
Example array:
$params = array('name' => 'john', 'gender' => 'male');
I have tried something like this but didn;t work:
$validator = Validator::make($params, [
'name' => 'required',
'gender' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors();
$message = $messages->first();
echo $message;
exit;
}
The validation is passing because the fields are in fact present. Use something like min or maxor size to validate the length of a string.
http://lumen.laravel.com/docs/validation#rule-required
Edit
I stand corrected. The required does actually seem to validate if it contains anything.
Update
To clarify; the code that is supposed to run if $validator->fails() doesn't ever run if the validation passes.
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.