Laravel Livewire validation won't allow me to output dynamic field names - php

I have a Livewire component that contains a booking form. I have some dynamic form fields
that are generated when a wired up button is pressed. The fields are displayed on the page by using array keys to make them unique:
<label for="">Contact Phone</label>
<input class="rounded border-gray-300 text-sm"
type="text"
name="attendee[{{ $key }}][contact_phone]">
Here are the validation rules inside the component controller:
$this->validate([
'course_date' => 'bail|required',
'attendee' => 'array|required',
'attendee.*.title' => 'required',
'attendee.*.first_name' => 'required',
'attendee.*.last_name' => 'required',
'attendee.*.email' => 'required|email:rfc,dns',
'attendee.*.contact_phone' => 'required|numeric|digits_between:10,13',
], [
'course_date.required' => 'You must select a date.',
'attendee.required' => 'Your booking must have at least one attendee.',
'attendee.*.title.required' => 'Title cannot be blank.',
'attendee.*.first_name.required' => 'First name cannot be blank.',
'attendee.*.last_name.required' => 'Last name cannot be blank.',
'attendee.*.email.required' => 'Please provide an email address.',
'attendee.*.email.email' => 'Please provide a valid email address.',
'attendee.*.contact_phone.required' => 'Please provide a contact phone number.',
'attendee.*.contact_phone.numeric' => 'Please provide a valid phone number.',
'attendee.*.contact_phone.digits_between' => 'Please provide a valid phone number.'
]);
If I display the errors all together at the top of the form like this:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
they work fine, and if I display the errors for the nested fields like this:
#error('attendee.0.title')
<span class="text-xs font-bold text-pink-900">{{ $message }}</span>
#enderror
However if I want to do this so I can have it work dynamically:
#error('attendee.{{ $key }}.title')
<span class="text-xs font-bold text-pink-900">{{ $message }}</span>
#enderror
it doesn't work. The error doesnt display at all.

Related

Laravel {{Form::Select}} not passing values to POST request parameters

this problem occured recently on a website on my development server, which runs Laravel 5.2.45. I have a form which I use to pass data through a POST request on a controller. On the form there are 2 multiselects, one for the available locations and one for the selected locations. The user can pass a location from the available locations to the selected locations. The problem is that once the form submits, the selected locations do not appear anywhere on the request parameters, but the available locations appear. This was working for a long time and suddendly it stopped working.
Available locations multiselect
<div class="form-group clearfix{{ $errors->has('available') ? ' has-error' : '' }}">
{!! Form::label('available', 'Available Locations', ['class'=> 'col-xs-12 pl-0 pr-0']) !!}
<div class="col-xs-12 pl-0 pr-0">
{{Form::select('available[]', $taskgroup['available'], null, ['id'=> 'multiselect', 'class'=> 'form-control', 'size'=> 8, 'multiple' => 'multiple']) }}
</div>
#if ($errors->has('available'))
<span class="help-block">{{ $errors->first('available') }}</span>
#endif
Selected locations multiselect
<div class="form-group clearfix{{ $errors->has('locations') ? ' has-error' : '' }}">
{!! Form::label('locations', 'Selected Locations', ['class'=> 'col-xs-12 pl-0 pr-0']) !!}
<div class="col-xs-12 pl-0 pr-0">
{{Form::select('locations[]', $taskgroup['locations'], null, ['id'=> 'multiselect_to', 'class'=> 'form-control', 'size'=> 8, 'multiple' => 'multiple']) }}
</div>
#if ($errors->has('locations'))
<span class="help-block">{{ $errors->first('locations') }}</span>
#endif
The part which handles the request in the controller
$taskgroup = Taskgroup::with('locations')->findOrFail($id);
$input = Input::all();
//dd($request,$input);
unset($input['available']);
if(!empty(array_values($input['media_url'])[0]['title'])){
$media_url = Taskgroup::sortArray($input['media_url'], 'order');
$input['media_url'] = json_encode(array('media' => $media_url));
} else {
unset($input['media_url']);
}
$messages = ['between' => 'The :attribute must be between :min - :max.'];
$validation = Validator::make($input, array_merge(Taskgroup::$rules, array('locations'=>'required|between:1,'.$input['max_users'])), $messages);
The uncommented data dump of the input data
"_method" => "PUT"
"_token" => "Token Here"
"name" => "Beer"
"short_description" => "Short Description<br>"
"_wysihtml5_mode" => "1"
"long_description" => "<div>Long Description</div>"
"pin_color" => "red"
"start_date" => "2018-12-03 09:00"
"end_date" => "2019-12-31 20:00"
"media_url" => array:1
"file_names" => array:1
"delete-file-85" => "0"
"delete-file-86" => "0"
"max_users" => "32"
"max_arrival_time" => "120"
"max_completion_time" => "30"
"client_id" => "22"
"q" => ""
"available" => array:977
"files" => array:1
This is my first post on the website, so please excuse any formatting errors. Thank you in advance.
Try to use
{!!Form::select(....)!!}

Display validation message Laravel 5.4

I have a validate like this :
TitleRequest.php:
public function rules()
{
return [
'title_name_report' => 'required|min:2',
'develop_code' => 'required',
];
}
public function messages()
{
return [
'title_name_report.required',
'title_name_report.min',
'develop_code.required'
];
}
Lang/vi/validation.php.
'title_name_report.required'=>"Please enter, :attribute !",
'title_name_report.min'=>"Min length is :attribute",
'develop_code.required'=>"Please enter :attribute !",
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
'attributes' => [],
views/title.blade.php
<input type="text" class="form-control" id="title_name_report" name="title_name_report"
value="{{old('title_name_report')}}">
#if($errors->has('title_name_report'))
<div class="error-text">
{{$errors->first('title_name_report')}}
</div>
#endif
I have 2 question :
1. How can I display exactly errors message, I have 2 rules but it always display the first rule's message. When I try enter 1 character it still display required message.
2. How can I use the langs file so I dont need put message into request files.
Please help me, thank so much !
You can show all validation errors with this :
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Put custom validation messages in resources/lang/xx/validation.php file in this format :
'custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
],
More Info : https://laravel.com/docs/5.4/validation#custom-error-messages
How can I display exactly errors message, I have 2 rules but it always display the first rule's message. When I try enter 1 character it still display required message.
Laravel will only validate your input in order. It will not return an
error message of the next rules until it didn't pass the first one.
How can I use the langs file so I dont need put message into request files.
You can find to localization details here. It is under
/resources/lang/en/validation.php
If you want to change the validation message tru Request file, You should do it like this
public function messages()
{
return [
'title_name_report.required' => "Title is required.",
'title_name_report.min' => "Title should not less than 2.",
'develop_code.required' => "Code is required.",
];
}

How to add validation on same database field for different names in Laravel?

I have a database users. It has an email field.
I have two input fields with names users[email] and manager.email. I want the validation of uniqueness to be on users table. Here is what have I tried it.
<div class="row">
<div class="form-group col-md-12">
<div class="col-md-8">{{ Form::input('text', 'users[email]', '', ['class' => "form-control", 'maxlength' => 255, 'id' => "userEmail", 'placeholder' => "Email Address"]) }}</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<div class="col-md-8">{{ Form::input('text', 'manager[email]', '', ['class' => "form-control", 'maxlength' => 255, 'id' => "email", 'placeholder' => "Manager Email Address"]) }}</div>
</div>
</div>
My validator is as follows:
$validationRules = ['users.email' => 'email|required|unique:users',
'manager.email' => 'email|required|unique:users',
];
So, when I validator it returns a message stating :
Unknown column 'manager.email' in 'where clause' (SQL: select count(*) as aggregate from `users` where `manager`.`email` = 'xyz#email.com')
Please guide me through this or suggest me a better option to resolve this problem.
I would imagine your issue is because you're not specifying the column name in your unique rule.
https://laravel.com/docs/5.2/validation#rule-unique (look under Specifying A Custom Column Name)
Try changing:
'manager.email' => 'email|required|unique:users'
to:
'manager.email' => 'email|required|unique:users,email'
Hope this helps!

How to return custom error message from controller method validation

How to return a custom error message using this format?
$this->validate($request, [
'thing' => 'required'
]);
to get custom error message you need to pass custom error message on third parameter,like that
$this->validate(
$request,
['thing' => 'required'],
['thing.required' => 'this is my custom error message for required']
);
For Multiple Field, Role and Field-Role Specific Message
$this->validate(
$request,
[
'uEmail' => 'required|unique:members',
'uPassword' => 'required|min:8'
],
[
'uEmail.required' => 'Please Provide Your Email Address For Better Communication, Thank You.',
'uEmail.unique' => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
'uPassword.required' => 'Password Is Required For Your Information Safety, Thank You.',
'uPassword.min' => 'Password Length Should Be More Than 8 Character Or Digit Or Mix, Thank You.',
]
);
https://laravel.com/docs/5.3/validation#working-with-error-messages
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
"In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file."
Strangely not present in the documentation, you can specify the first parameter as the validation rules & the second parameter as the message format directly off of the Illuminate/Http/Request instead of invoking $this or the Validator class.
public function createCustomer(Request $request)
{
# Let's assume you have a $request->input('customer') parameter POSTed.
$request->validate([
'customer.name' => 'required|max:255',
'customer.email' => 'required|email|unique:customers,email',
'customer.mobile' => 'required|unique:customers,mobile',
], [
'customer.name.required' => 'A customer name is required.',
'customer.email.required' => 'A customer email is required',
'customer.email.email' => 'Please specify a real email',
'customer.email.unique' => 'You have a customer with that email.',
'customer.mobile.required' => 'A mobile number is required.',
'customer.mobile.unique' => 'You have a customer with that mobile.',
]);
}
You need to first add following lines in view page where you want to show the Error message:
<div class="row">
<div class="col-md-4 col-md-offset-4 error">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
Here is a demo controller by which error message will appear on that page:
public function saveUser(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required|unique:users',
]);
$user=new User();
$user->name= $request->Input(['name']);
$user->email=$request->Input(['email']);
$user->save();
return redirect('getUser');
}
For details You can follow the Blog post.
Besides that you can follow laravel official doc as well Validation.

Disabled select doesn't validate when order is submitted in blade template

I have this condition in my order.blade
<div class="form-group">
<label for="shipping_method" class="control-label">Shipping method:</label>
#if( $total < $free_delivery )
{{ Form::select('shipping_method', [
Settings::SETTINGS_SHIPPING_NORMAL => 'Normal Delivery',
Settings::SETTINGS_SHIPPING_EXPRESS => sprintf('Express Delivery - $%.2f', Settings::getOption('express_shipping_cost'))
], null, ['class' => 'form-control']) }}
#else
{{ Form::select('shipping_method', [
Settings::SETTINGS_SHIPPING_FREE => 'Free Delivery'
], null, ['class' => 'form-control','disabled']) }}
#endif
</div>
When user make order for more than X amount he gets free delivery. The problem here is that when I try to submit order with free delivery i.e. in else block I've got that shipping method is required.
In IF block is working. Why doesn't get the name of else block? Here is my validation rule
$validatorRules = array(
'captcha' => 'required|captcha',
'shipping_method' => 'required|in:' . implode(',', [Settings::SETTINGS_SHIPPING_NORMAL, Settings::SETTINGS_SHIPPING_EXPRESS, Settings::SETTINGS_SHIPPING_FREE])
);
In a form if an element is disabled, it's not send with your request, you can enable it since you only have this in your select when shipping is free.
If you really want it disable you can catch when your form is submitted in JS, and the value to and hidden field with the same name or just add an hidden field in your form
{{ Form::hidden('shipping_method', /* Params */) }}
{{ Form::select('shipping_method', [
Settings::SETTINGS_SHIPPING_FREE => 'Free Delivery'
], null, ['class' => 'form-control','disabled']) }}

Categories