Custom error message in Laravel - php

I am validating an array in Laravel. I get "0.id has already been taken." in default error message. So I added a 2nd parameter in my validator: 'unique' =>':attribute has already been taken. Please fix your data in spreadsheet.' and shows "0.id has already been taken. Please fix your data in spreadsheet.". I added the 3rd parameter which is the custom attribute. ['*.id' =>'Student ID']. But I want to have a message like this: ID has already been taken. Please fix your data in spreadsheet in line 1.
Here's my full validation code:
$validate = $request - > validate([
'*.id' => 'required|unique:students|numeric',
'*.rfid_number' => 'required|unique:students|numeric',
'*.first_name' => 'required|alpha|max:100',
'*.middle_name' => 'alpha|max:100|nullable',
'*.last_name' => 'required|string|max:100',
'*.name_extension' => 'alpha|max:10|nullable',
'*.email' => 'required|email|unique:students',
'*.photo' => 'string|nullable',
'*.house_number' => 'required|integer',
'*.barangay' => 'required|alpha|max:100',
'*.city' => 'required|alpha|max:100',
'*.province' => 'required|string|max:100',
'*.zip_code' => 'required|integer',
'*.birth_date' => 'required|date|max:100',
'*.birth_place' => 'string|max:200',
'*.gender' => 'required|alpha',
'*.religion' => 'alpha|max:100|nullable',
'*.landline_number' => 'numeric|max:20|nullable',
'*.mobile_number' => 'required',
'*.father_name' => 'string|max:200|required',
'*.father_occupation' => 'string|max:200|nullable',
'*.mother_name' => 'string|max:200|required',
'*.mother_occupation' => 'string|max:200|nullable',
'*.guardian_name' => 'string|max:200|required',
'*.guardian_occupation' => 'string|max:200|nullable',
'*.guardian_address' => 'string|max:200|nullable',
'*.year' => 'integer|max:10|required',
'*.section' => 'alpha|max:200|required'
], [
'unique' => ':attribute has already been taken. Please fix your data in spreadsheet.'
], [ //attributes
'*.id' => 'Student ID'
]);

Something like this would do the trick:
$validate = $request->validate([
//
], [
//
],
collect($request->all())->keys()->flatMap(function ($index) {
return ["$index.id" => 'ID'];
})->toArray());
Iterate over all the indexes so you end up with something like:
[
'0.id' => 'ID',
'1.id' => 'ID',
'2.id' => 'ID',
'3.id' => 'ID',
'4.id' => 'ID',
'5.id' => 'ID',
'6.id' => 'ID',
'7.id' => 'ID',
]
As your final array to the validator

Related

Laravel: Edit value only if it appears in the request?

in my app the user can update the info of stripe connected account, however I ONLY want to actullay update the value of the fields that appear in the request payload, I could do this with a simple if check but the way I update the stripe array method makes this issue more complicated .
Is there any syntax sugar or trick to make this easier.
How my update method looks;
public function editConnectedAccount(Request $request)
{
$account = Account::retrieve($request->connectedAccountId);
Account::update(
$request->connectedAccountId,
[
'type' => 'custom',
'country' => 'ES',
'email' => $request->userEmail,
'business_type' => 'individual',
'tos_acceptance' => [ 'date' => Carbon::now()->timestamp, 'ip' => '83.46.154.71' ],
'individual' =>
[
'dob' => [ 'day' => $request->userDOBday, 'month' => $request->userDOBmonth, 'year' => $request->userDOByear ],
'first_name' => $request->userName,
'email' => $request->userEmail,
'phone' => $request->userPhone,
'last_name' => $request->userSurname,
//'ssn_last_4' => 7871,
'address' => [ 'city' => $request->userBusinessCity, 'line1' => $request->userBusinessAddress, 'postal_code' => $request->userBusinessZipCode, 'state' => $request->userBusinessCity ]
],
'business_profile' =>
[
'mcc' => 5812, //got it
'description' => '',
//'url' => 'https://www.youtube.com/?hl=es&gl=ES', //got it
],
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
]
);
return response()->json([
'account' => $account,
], 200);
Consider using a Form Request where you preform validation. This will neaten up your controller for a start and also make validation (never trust user input!) reusable.
Assuming validation is successful, calling $request->validated() from inside your controller method will return only the fields present and validated. You can then use either fill($request->validated()) or update($request->validated()).

Create Associative Array with Foreach, Insert into existing Associative Array

Hello.
I currently have a problem with the AWS Route-53 API. To create a record you need to call a function, which itself needs an array of inputs.
I want to create a record set here and for that I have some POST values. One of them, $_POST['record_value'], is a textarea and has multiple lines. I loop through them. This is to enable multiple values for one record. The code is as follows when you hardcode it as one value in ResourceRecords;
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
[
'Value' => $recordValue
],
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
Hower. I want to make ResourceRecords dynamically. For every line in the textarea I need a new set of the following part of the code;
[
'Value' => $recordValue
],
What I thought is the following;
$newData = [];
foreach(explode("\r\n", $recordValue) as $valLine) {
$newData[] = ["Value" => $valLine];
}
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
$newData
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
However, this seems to return an exception: Found 1 error while validating the input provided for the ChangeResourceRecordSets operation:↵[ChangeBatch][Changes][0][ResourceRecordSet][ResourceRecords][0] must be an associative array. Found array(1).
Am I building the array wrong or am I doing this wrong alltogether?
$newData is already an array, you don't need to wrap it in another array.
'ResourceRecords' => $newData,

How to add additional info into php array

I use this php code:
public function checkout(&$order, &$response)
{
$settings = Settings::get($order->seller_id);
$readon= 'maksājums';
$readon= $order->id;
$order->custom([
'payment_details' => [
'bank_name' => [ 'label' => $this->_->_('Bank Name'), 'value' => $settings->bank_name ],
'account_owner' => [ 'label' => $this->_->_('Account Owner'), 'value' => $settings->account_owner ],
//'bic' => [ 'label' => $this->_->_('BIC/SWIFT'), 'value' => $settings->bic ],
'iban' => ['label' => $this->_->_('IBAN'), 'value' => $settings->iban ],
'reason' => [ 'label' => $this->_->_('Reason for Payment'), 'value' => $readon],
],
]);
$response = [];
$response['redirect'] = $this->meta('manual_url');
return Payment::STATUS_OK;
}
Problem is that I want to add additional text on value readon. Right now $readon show only order number, but I want that it display text like "Please make payment for Order No.$order->id"
Just concatenate the string with what you need. Like this,
$readon= "Please make payment for Order No. ".$order->id;

How test required_if with more than one value

I am newbie with Laravel and picked up a system to give maintenance.
I have this rule:
protected $rules = array(
'per_vlr_principal_rte' => 'required_if:per_fase_processual,2',
'per_vlr_juros_rte' => 'required_if:per_fase_processual,2',
'per_vlr_principal_rdo' => 'required_if:per_fase_processual,1,2',
'per_vlr_juros_rdo' => 'required_if:per_fase_processual,1,2',
'per_vlr_principal_perito' => 'required_if:per_fase_processual,2',
'per_vlr_juros_perito' => 'required_if:per_fase_processual,2',
'per_vlr_homologado' => 'required_if:per_fase_processual,2',
'per_qte_rte' => 'required',
'per_competencias' => 'required',
'per_qte_laudo' => 'required',
'per_dt_calculo' => 'required'
);
I'd like to know if the code below is correct:
'per_vlr_principal_rdo' => 'required_if:per_fase_processual,1,2',
'per_vlr_juros_rdo' => 'required_if:per_fase_processual,1,2',
The validation occurs only when the value is 1.
How to fix it?

ZF2 - Need to display specific error message on specific condition failure

I am using ZF2 form validation.I have to validate two fields USERNAME and PASSWORD.
everything is working fine but I am getting message like
Please enter username.
Username can not be less than 3 characters.
Please enter password.
Password can not be less than 6 characters.
If user is not entering any value then only this message should display
Please enter username.
Please enter password.
I don't want do display all the error messages on a field on failure.
Thanks in advance.
I got the answer :
In order to break the validation chain in ZF2 , we have to use
'break_chain_on_failure' => true
$this->add(
array(
'name' => 'usernmae',
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim')
),
'validators' => array(
array('name' => 'NotEmpty',
'options' => array('encoding' => 'UTF-8',
'messages' => array(
NotEmpty::IS_EMPTY => 'Please enter username')),
'break_chain_on_failure' => true),
array(
'name' => 'Zend\Validator\StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 30,
'messages' => array(
StringLength::TOO_LONG => 'Username can not be more than 30 characters long',
StringLength::TOO_SHORT => 'Username can not be less than 3 characters.')
),
'break_chain_on_failure' => true
)
)
)
);
My Blog : http://programming-tips.in
Zend_Validate allow you to break validators chain if certain vaildation fails. The second parameter of addValidator() function $breakChainOnFailure should be TRUE in this case.
$validatorChain = new Zend_Validate();
$validatorChain->addValidator(new Zend_Validate_NotEmpty(), TRUE)
->addValidator(new Zend_Validate_StringLength(6, 12));
You can also set the 'error_message' key, for example:
'email' => [
'required' => true,
'error_message' => 'Incorrect email address ',
'filters' => [
[
'name' => 'StripTags',
],
[
'name' => 'StringToLower',
]
],
'validators' => [
[
'name' => 'EmailAddress',
'break_chain_on_failure' => true
]
]
],

Categories