How to validate an ID which should be in given array - Laravel - laravel

I have an array which is
array (
0 => 1,
1 => 7,
2 => 11,
3 => 8,
4 => 5,
)
Now I want to validate a field status which should be in the given list.
$validation = Validator::make($req->all(),[
'status.*.id' => 'required'
]);
How can I validate the status? Can anyone suggest any solution?
Thank You.

Laravel has an option to validate a value compare to a given array of data:
//At the top of your class add the correct Rule namespace.
use Illuminate\Validation\Rule;
$yourarray = [
0 => 1,
1 => 7,
2 => 11,
3 => 8,
4 => 5,
];
$validation = Validator::make($req->all(),[
'status.*.id' => ['required',Rule::in($yourarray)]
]);
For further details follow the official documentation here

<p>
<input type="text" name="person[1][id]">
<input type="text" name="person[1][name]">
</p>
<p>
<input type="text" name="person[2][id]">
<input type="text" name="person[2][name]">
</p>
Now you can validate the requested data as below:
$v = Validator::make($request->all(), [
'person.*.id' => 'exists:users.id',
'person.*.name' => 'required:string',
]);

Related

How to resolve Array to String conversion error Laravel

I'm new to laravel and i encountered an array to string conversion error while trying to send tags select form data to sync with my blogs table.
Below is blade snippet that retrieves tags from the database
<div class="form-group">
<label for="tag" class="control-label">Tags</label>
{!! Form::select('tag[]', $tags, old('tag'), ['class' => 'form-control select2', 'multiple' => 'multiple', 'id' => 'add-tag' ]) !!}
</div>
The BlogsController
$blog_data = request()->validate([
'tag.*' => 'required'
]);
blogs = Blog::create( $blog_data );
$blogs->tags()->sync((array)request()->input('tag'));
when i perform a dd on request()->tag
array:2 [▼
0 => "1"
1 => "2"
]
Just use like this
$blogs = Blog::create( $blog_data );
If insert then use like this
$blogs->tags()->attach($request->tag);
If update then use like this
$blogs->tags()->sync($request->tag);
Thank you, i was able to remove this line of code and it worked
tag.*' => 'required'

Textarea with Laravel Collective

Hello friends I need make a Textarea with Laravel Collective, regulary I use:
<textarea id="txt" name="txt" maxlength="1900" class="form-control" rows=1" onkeypress="return nameFunction(event);">My text</textarea>
How to create a textarea wiht Laravel Collective?
Try like this:
Form::textarea('My text', null, [
'class' => 'form-control',
'rows' => 1,
'name' => 'txt',
'id' => 'txt',
'onkeypress' => "return nameFunction(event);"
])

Why it shows an error in the store() conferece?

I have this code to store a conference. There is a form field that is for the user to select the available payment methods. The form field is like this:
<div class="form-group">
<label for="inputName">
Select the payment methods</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="payment_mb" id="payment_mb">
<label class="form-check-label" for="exampleRadios1">
MB
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="payment_c" id="payment_c">
<label class="form-check-label" for="exampleRadios1">
Credit Card
</label>
</div>
</div>
The code to store is like below.
But it shows an error:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value:
'on' for column 'payment_mb' at row 1 (SQL:
insert into `conferences` (`name`, `organizer_id`,
`organizer_name`, `organizer_email`, `invoice_entity`,
`payment_mb`, `updated_at`, `created_at`)
values (a, 2, John W, emailtest#test.com, 1,
on, 2018-07-25 19:17:26, 2018-07-25 19:17:26))
Do you know why?
public function store(Request $request)
{
$conference = Conference::create([
'name' => $request->name,
'city' => $request->city,
'organizer_id' => Auth::id(),
'organizer_name' => $request->organizer_name,
'organizer_email' => $request->organizer_email,
'payment_mb' =>$request->payment_mb ? : 0,
'payment_c' => $request->payment_c ? : 0
]);
$conference->categories()->attach($request->categories);
$conference->save();
Session::flash('success', 'conference created.');
}
The $request->all() shows like:
array:25 [▼
"_token" => ""
"name" => "test"
"organizer_name" => "John W"
"organizer_email" => "..."
"payment_mb" => "on"
"payment_c" => "on"
"invoice_issuer" => "1"
]
Well on wouldn't be an int value. Your request has the value 'on' for that field.
'payment_mb' =>$request->payment_mb ? : 0,
You could maybe try:
'payment_mb' => (int) boolval($request->payment_mb),
Or even just:
'payment_mb' => (bool) $request->payment_mb,
PHP Docs - boolval
You could also actually set a value for the checkbox to be a '1' or something like that.
Some validation might be good.
Update
I think i was looking for filter_var:
filter_var($thatInput, FILTER_VALIDATE_BOOLEAN);
// 'on' => true
// null => false
// 'off' => false
Are you sure this is the correct store code?
payment_c does not appear in the sql statement even though it was set in your code.

PHP Laravel Validation data key names

I got such problem.
What I want to do - is to make 1 place for validation rules for a user data. These data consists of Patient, Address and other objects.
So I created rules:
protected function validationRules()
{
return [
'Patient.firstName' => 'required|string|min:2',
'Patient.lastName' => 'required|string',
'Patient.sex' => 'required|string',
'Address.city' => 'required|string',
'Address.states' => 'required|string',
'Address.address1' => 'required|string|min:2',
'Address.zip' => 'required|string|min:2',
'Phone.mobileArea' => 'string|min:3|required_with:Phone.mobilePhone',
'Phone.mobilePhone' => 'string|min:7|required_with:Phone.mobileArea',
'Phone.homePhone' => 'string|min:7|required_with:Phone.homeArea',
'Phone.homeArea' => 'string|min:3|required_with:Phone.homePhone',
];
}
In form i have inputs like
<input id="firstName" type="text" class="form-control" name="Patient[firstName]" value="{{ $user->getFirstName() }}" required autofocus placeholder="First Name">
And on save everything works correctly.
The code
$this->validate($request, $this->validationRules());
Performs validation very well. BUT....
On another place, when I want to show that some information is missing in the user profile, I perform such validation and its failed:
$validator = Validator::make([
'Patient[firstName]' => $user->getFirstName(),
'Patient[lastName]' => $user->getLastName(),
'Patient.lastName' => $user->getLastName(),
'Patient->lastName' => $user->getLastName(),
'Patient.sex' => $user->getSex(),
'Address.city' => $address->getCity(),
'Address.states' => $address->getState(),
'Address.address1' => $address->getStreet1(),
'Address.zip' => $address->getZip(),
'Phone.mobileArea' => $mobilePhone->getArea(),
'Phone.mobilePhone' => $mobilePhone->getNumber(),
'Phone.homePhone' => $homePhone->getArea(),
'Phone.homeArea' => $homePhone->getNumber(),
], $this->validationRules());
As you can see, i tried different variations of naming Patient->lastName key in data array. But i still have error that last name is required.
When i print validator i can see such structure:
Validator {#300 ▼
#data: array:12 [▼
"Patient[firstName]" => ""
"Patient[lastName]" => "Colohanin"
"Patient->lastName" => "Colohanin"
"Patient->sex" => "female"
"Address->city" => "GOSHEN2"
"Address->states" => "NY"
"Address->address1" => "Aleco Russo 59/1 a.68"
"Address->zip" => "109242"
"Phone->mobileArea" => "793"
"Phone->mobilePhone" => "906990"
"Phone->homePhone" => "022"
"Phone->homeArea" => "3322278"
]
#initialRules: array:1 [▼
"Patient.lastName" => "required|string"
]
}
As I understand, the validator has rules for "Patient.lastName" but in data array Laravel transform this key to object and Validator can't find this key in data bag. In result, I have error - > patient last name required(for testing purposes, I removed other rules)
So there is my question. Does anyone know, how to set data array in "dot" sintancs? How should i name "Patient.lastName" in data array(first parameter in Validator::make())?
The rewriting keys using underscore doesn't accept(patient_firstName)
Suddenly i found that laravel helper have array_set helper for such arrays.
So in result:
$data = [
'Patient[firstName]' => $user->getFirstName(),
'Patient[lastName]' => $user->getLastName(),
'Patient["lastName"]' => $user->getLastName(),
'Patient.lastName' => $user->getLastName(),
'Patient->lastName' => $user->getLastName(),
'Address.city' => $address->getCity(),
'Address.states' => $address->getState(),
'Address.address1' => $address->getStreet1(),
'Address.zip' => $address->getZip(),
'Phone.mobileArea' => $mobilePhone->getArea(),
'Phone.mobilePhone' => $mobilePhone->getNumber(),
'Phone.homePhone' => $homePhone->getArea(),
'Phone.homeArea' => $homePhone->getNumber(),
];
Fails validation, but if you add elements throw array_set helper it helps
array_set
array_set($data, 'Patient.lastName' , $user->getLastName());
After that, validation by lastName is no longer fails.
Hope it helps somebody
try this:
$this->validate($request->get('Patient'), $this->validationRules());
form input:
all name changes it to :
<input id="firstName" type="text" class="form-control" name="Patient[firstName]" value="{{ $user->getFirstName() }}" required autofocus placeholder="First Name">
<input id="mobileArea" type="text" class="form-control" name="Patient[mobileArea]" value="{{ $user->mobileArea() }}" required autofocus placeholder="mobileArea"
>
and change all validationrules using:
protected function validationRules()
{
return [
'Patient.firstName' => 'required|string|min:2',
'Patient.lastName' => 'required|string',
'Patient.sex' => 'required|string',
'Patient.city' => 'required|string',
'Patient.states' => 'required|string',
'Patient.address1' => 'required|string|min:2',
'Patient.zip' => 'required|string|min:2',
'Patient.mobileArea' => 'string|min:3|required_with:Patient.mobilePhone',
'Patient.mobilePhone' => 'string|min:7|required_with:Patient.mobileArea',
'Patient.homePhone' => 'string|min:7|required_with:Patient.homeArea',
'Patient.homeArea' => 'string|min:3|required_with:Patient.homePhone',
];
}
Hope it help

Field is required when other three fields are empty

I have 4 input fields. 1 of them has to be filled.
My fields :
<input name="name" placeholder="Name">
<input name="hair_style" placeholder="Style">
<input name="hair_color" placeholder="Color">
<input name="options" placeholder="Options">
My function
$this->validate($request, [
'name' => 'required_if:hair_style,0,',
]);
So when hair_style is 0. Input field name has to be filled. This works but.. I want it like this below but I don't know how:
$this->validate($request, [
'name' => 'required_if:hair_style,empty AND hair_color,empty AND options,empty,',
]);
It has to work like this. When hair_style, hair_color and options are empty name has to be filled. But is this possible with required_if ?
You can try as:
'name' => 'required_if:hair_style,0|required_if:hair_color,0||required_if:options,0',
Update
You can conditionally add rules as:
$v = Validator::make($data, [
'name' => 'min:1',
]);
$v->sometimes('name', 'required', function($input) {
return ($input->hair_style == 0 && $input->hair_color == 0 && $input->options == 0);
});
You can add more logics in the closure if you required...like empty checks.
So all I had to do was :
$this->validate($request, [
'name' => 'required_without_all:hair_style, hair_color, options',
]);
for more information check https://laravel.com/docs/5.3/validation#rule-required-without-all

Resources