get checked option value in laravel - php

I have input group include 2 options checkbox and input field.
I want to get value of input field only if checkbox is checked
otherwise ignore that input field.
Codes
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" checked="checked">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
currently I get all my inputs in my controller regardless they are checked or not:
$column = $request->except('_token');
How do I pass this to my controller function?
UPDATE
as requested : my code $list dd is:
array:27 [▼
0 => "id"
1 => "title"
2 => "slug"
3 => "imageOne"
4 => "imageTwo"
5 => "short_description"
6 => "description"
7 => "price"
8 => "meta_description"
9 => "meta_tags"
10 => "arrivalDays"
11 => "height"
12 => "weight"
13 => "lenght"
14 => "width"
15 => "sku"
16 => "stock"
17 => "label"
18 => "label_from"
19 => "label_to"
20 => "label_color"
21 => "status_id"
22 => "brand_id"
23 => "category_id"
24 => "subcategory_id"
25 => "created_at"
26 => "updated_at"
]
UPDATE 2
To be clear how it works exactly i included screenshot
SEE IT

1) change the name of checkbox to cb[] and input to input[]
#php
$no = 0;
#endphp
#foreach($list as $columns)
#php
$no+=1;
#endphp
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[{{$no}}]" checked="checked">
</span>
<input type="text" name="input[{{$no}}]" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
2)filter your $request and include just the checked checkbox
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getRealInput[$key] = $input['input'][$key];
}
}
return $getRealInput;

Try This:
1) first of all mention checkbox name like this :
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input name="checkbox" type="checkbox" checked="checked">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
2) In Controller try this:
$inputs = asset($request->checkbox) && $request->checkbox !='' ? $request->except('_token') : []; //if you want to remove input fields use unset inputs instead of []
dd($inputs)

You could name the checkbox as an array
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[]" value="{{ $columns }}">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
and in your controller you could get the checked items as
foreach ($request->cb as $checked) {
$request->{$checked} // The textbox corresponding to the selected checkbox
}

You should try this:
Updated Answer:
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="columns[]" value="{{ $columns }}">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
In controller :
$columns = $request->columns;
print_r($columns);

First of all, identify each checkboxes with unique names(use columns[]).
Here I guess you don't expect manual entry(modification) as you populate the value of $columns in your text input field. If so, yoou could use a label instead:
#foreach($list as $key => $columns)
<div class="input-group">
<span class="input-group-addon">
<input name="columns[]" type="checkbox" value={{$key}} checked="checked">
</span>
<label class="form-control">{{$columns}}</label>
</div>
#endforeach
UPDATE:
VIEW
#foreach($list as $key => $columns)
<span class="input-group-addon">
<input name="col_keys[]" type="checkbox" value={{$key}} checked="checked">
</span>
<input type="text" name="col_texts[]" value="{{$columns}}" class="form-control">
#endforeach
CONTROLLER
Now $request->col_keys will have an array of keys that are valid for $request->col_texts. So do a sorting:
$valid_keys = $request->col_keys;
$all_texts = $reqest->col_texts;
foreach($all_texts as $key => $item) {
if (($key = array_search($key, $valid_keys)) === false) {
unset($all_texts($key));
}
}

SOLVED
First of all I have to thank everyone who tried to help me solve this issue specially Wahyu Fadzar. Here is how I solved my issue:
I changed my blade code to:
#php $no = 0; #endphp //Wahyu Fadzar idea
#foreach($list as $columns)
#php $no+=1; #endphp //Wahyu Fadzar idea
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[{{$no}}]" checked="checked"> //Wahyu Fadzar idea
</span>
<input type="text" name="customname[{{$no}}]" value="{{$columns}}" //Wahyu Fadzar ideaclass="form-control">
<input type="hidden" name="defaultname[{{$no}}]" value="{{$columns}}"> // Added
</div><!-- /input-group -->
#endforeach
Controller
public function export(Request $request) {
// defaultname that i added in my blade used here (explaination below)
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getRealInput[$key] = $input['defaultname'][$key];
}
}
$products = Product::select($getRealInput)->get(); //getting table selected columns
Excel::create('products', function($excel) use($products, $request) {
$excel->sheet('sheet 1', function($sheet) use($products, $request){
//Wahyu Fadzar code used here to get selected columns data
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getCustomInput[$key] = $input['customname'][$key];
}
}
$sheet->fromArray($products, null, 'A1', false, false);
$sheet->row(1, $getCustomInput);
});
})->export('csv');
return redirect()->back();
}
Explanations
I had issue before when I used Wahyu code it would remove my inputs from CSV file as i unchecked them, but their data still exist in my file
so I added
< input type = " hidden " name = " defaultname[{{$no}}] " value = " {{$columns}} " >
and by this i will get my default column names even if i edit it for export. otherwise it would return error, eg. I changed my title column to name it says there is no column name! so by this my title column will stay title for select query.
I used it in:
$products = Product::select($getRealInput)->get();
I used Wahyu code in my export part in order to get custom input names for my CSV file and not the default ones.
< input type = " text " name = " customname[{{$no}}] " value = "
{{$columns}} " class = " form-control " >
goes to:
if ($value== 'on') {
$getCustomInput[$key] = $input['customname'][$key];
}
inside my export query.
Hope it help others as well.
THANK YOU ALL.

Related

How do I update records in a loop in Laravel 8

I am developing a student portal in Laravel 8. I would love to update the class subjects.
Here is my controller
public function UpdateAssignSubject(Request $request, $class_id)
{
if ($request->subject_id == null) {
$notification = [
'message' => 'Sorry You did not Select any Subject',
'alert-type' => 'error'
];
return redirect()->route('assign.subject.edit', $class_id)->with($notification);
} else {
$countClass = count($request->subject_id);
AssignSubject::where('class_id', $class_id)->delete();
for ($i = 0; $i < $countClass; $i++) {
$assign_subject = new AssignSubject();
$assign_subject->class_id = $request->class_id;
$assign_subject->subject_id = $request->subject_id[$i];
$assign_subject->full_mark = $request->full_mark[$i];
$assign_subject->pass_mark = $request->pass_mark[$i];
$assign_subject->subjective_mark = $request->subjective_mark[$i];
$assign_subject->save();
} // End For Loop
}// end Else
$notification = [
'message' => 'Assigned Subject Updated Successfully',
'alert-type' => 'success'
];
}
This very piece of code AssignSubject::where('class_id', $class_id)->delete(); is giving me issues since I am using the AssignSubject as a pivot table thus deleting the Id's produces errors in the long run.
Here is my view
#foreach($subjects as $subject)
<option value="{{ $subject->id }}" {{ ($edit->subject_id == $subject->id)? "selected": ""
}}>{{ $subject->name }}</option>
#endforeach
<div class="form-group">
<h5 style="color:black">Full Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="full_mark[]" value="{{ $edit->full_mark }}" class="form-control"
style="background-color: rgb(176, 172, 216);color:black" >
</div>
<div class="col-md-2">
<div class="form-group">
<h5 style="color:black">Pass Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="pass_mark[]" value="{{ $edit->pass_mark }}" class="form-control"
style="background-color: rgb(176, 172, 216);color:black">
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<h5 style="color:black">Subjective Mark <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="subjective_mark[]" value="{{ $edit->subjective_mark }}" class="form-
control" style="background-color: rgb(176, 172, 216);color:black">
</div>
</div>
</div>
Please how can I update the record without deleting first. Any help would be greatly appreciated.
Instead of deleting all entities, you can simply update them if they do exist.
In case they do not, you need to create a new one, like you did in your for loop.
I adjusted your code, to check if a subject already exists, if it does it updates it, otherwise a new one is created
$countClass = count($request->subject_id);
// remove this line
// AssignSubject::where('class_id', $class_id)->delete();
for ($i = 0; $i < $countClass; $i++) {
// a class can only have each subject 1 time, so you can filter for it
$entity = AssignSubject::where('class_id', $class_id)
->where('subject_id', $request->subject_id[$i])
->first();
// if entry does not exist, ->first() will return null, in this case, create a new entity
$assign_subject = $entity ?? new AssignSubject();
// update columns
$assign_subject->class_id = $request->class_id;
$assign_subject->subject_id = $request->subject_id[$i];
$assign_subject->full_mark = $request->full_mark[$i];
$assign_subject->pass_mark = $request->pass_mark[$i];
$assign_subject->subjective_mark = $request->subjective_mark[$i];
// save changes
$assign_subject->save();
}

Posting arrays Laravel 8 - values returning as NULL

I am trying to post an array from my form to database
The form fields are showing up as NULL
HTML form excerpt:
#foreach (range(0,9) as $x)
<div class="row m-3 credit-card-details">
<div class="col-lg-4">
<div class="form-group">
<label for="financeCompany-{{ $x }}">Finance Company name #{{ $x }}</label>
<input type="text" class="form-control" id="financeCompany-{{ $x }}" name="creditCards[{{ $x }}][financeCompany]" value="" placeholder="Finance Company Name" />
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="creditLimit-{{ $x }}">Credit limit</label>
<input type="text" class="form-control" id="creditLimit-{{ $x }}" name="creditCards[{{ $x }}][creditLimit]" value="" placeholder="$" />
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="consolidate-{{ $x }}">Consolidate this card?</label>
<input type="text" class="form-control" name="creditCards[{{ $x }}][consolidate]" id="consolidate-{{ $x }}" value="" />
</div>
</div>
</div>
#endforeach
My Controller:
public function store(CreateApplicationRequest $request, Applicant $applicant, CreditCard $creditCard)
{
$applicant = Applicant::create([
...
]);
$application = $applicant->application()->create([
...
]);
$creditCards = $request->input('creditCards');
foreach ($creditCards as $creditCard)
{
$application->creditCards()->create([
'financeCompany' => $request->input('financeCompany'),
'creditLimit' => $request->input('creditLimit'),
'consolidate' => $request->input('consolidate')
]);
}
...
}
My dd results are showing up like this:
The right amount of records are being created in my credit_cards table and the application_id, created_at and updated_at fields are being correctly recorded, however the financeCompany, creditLimit and consolidate fields (from the form) are all showing up as NULL.
Database:
CreditCard model:
protected $fillable = [
'application_id',
'financeCompany',
'creditLimit',
'consolidate'
];
Only the application_id is being collected by the database.
Still quite new at this, any help would be greatly appreciated.
so your request() has $creditCards by the look of it. The values you are interested in seems to be within $creditCards
you need to do something like this
collect($creditCards)
->each(fn ($creditCard) => $application->creditCards()
->create([
'financeCompany' => creditCard['financeCompany'],
'creditLimit' => creditCard['creditLimit'],
'consolidate' => creditCard['consolidate']
])
);
or if you want to use foreach
foreach ($creditCards as $creditCard) {
$application->creditCards()->create([
'financeCompany' => creditCard('financeCompany'),
'creditLimit' => creditCard('creditLimit'),
'consolidate' => creditCard('consolidate')
]);
}
Make sure you have them declared in the $fillable in your model otherwise the ORM will not pick them up.
Example:
protected $fillable = [
'financeCompany',
'creditLimit',
'consolidate',
];

Problem with storing checkbox values in database

I am trying to store my checkbox values in database. I have these three tables.
fields
id name
1 gender
2 looking_for
field_values (here field_id references id on fields table)
id field_id value label
1 1 1 Men
2 1 2 Women
3 2 3 Relationship
4 2 4 Friendship
5 2 5 Marriage
user_interests (here field_id references field_id on field_values table and value_id references value on field_values table)
user_id field_id value_id
1 1 2
1 2 4
1 2 5
gender in blade uses option values and looking_for uses checkbox values. I made one function that is trying to update both of them. I use two foreaches in my function and I am able to successfully update gender option, but I am unable to update looking_for option. When I click submit button nothing happens, also when I dump anything inside that foreach that is supposed to update checkboxes it doesn't dump. Any help is greatly appreciated. Here is my code.
web.php
Route::patch('profile/interests', 'UserProfileController#updateInterestsData')->name('profile.update.interests.data');
UserProfileController.php
public function updateInterestsData(UpdateInterestsDataRequest $request)
{
$user = User::with('userProfile')->where('id', Auth::user()->id)->firstOrFail();
$request->validated();
$userId = $request->input('user_id') ? $request->input('user_id') : Auth::user()->id;
$data = $request->all();
$options = [
'gender' => 1,
'looking_for' => 2
];
foreach ($options as $fieldName => $fieldId) {
if (! empty($data[$fieldName])) {
DB::table('user_interests')
->where('user_id', $userId)
->where('field_id', $fieldId)
->delete();
if (is_array($data[$fieldName])) { // CHECKBOX FIELDS AND HERE IT DOESN'T WORK!!!
//dd('DIE!!!!!!') IT DOESN'T ENTER HERE!!!
foreach ($data[$fieldName] as $key => $value) {
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $value
]);
}
} else { // SELECT FIELDS!!!
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $data[$fieldName]
]);
}
}
}
$user->userProfile->update(
[
'age_from_preference' => $request->age_from_preference,
'age_to_preference' => $request->age_to_preference,
'updated_at' => Carbon::now()
]
);
$request->user()->save();
return redirect()->route('profile.show', [$user->username]);
}
index.blade.php
<form action="{{ route('profile.update.interests.data') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group">
<span>Interessiert an</span>
{{-- wrong value - selected --}}
#isset($options)
#foreach($options as $name => $fieldData)
#if ($name == 'gender')
<div class="selectHolder">
<select name="{{ $name }}">
<option selected="true" disabled="disabled" value="" style="display:none">bitte auswählen</option>
#foreach($fieldData['data'] as $value => $label)
<option value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'selected' : '') : '' }}>
{{ $label }}
</option>
#endforeach
</select>
</div>
<?php
unset($options[$name]);
?>
#endif
#endforeach
#endisset
</div>
<div class="form-group">
<span>Im Alter von</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_from_preference ?? "" }}" name="age_from_preference">
<span>Jahren bis</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_to_preference ?? "" }}" name="age_to_preference">
<span>Jahren</span>
</div>
{{-- wrong value - checked --}}
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name.'-'.$value }}" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset
<div class="form-group">
<label for="" class="textBold">Button</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
code for $options variable
public static function getProfileLookingForDisplayOptions()
{
$options = [
'gender' => ['id' => 1, 'label' => "Interessiert an"],
'looking_for' => ['id' => 2, 'label' => ""]
];
$data_options = [];
foreach ($options as $field => $value) {
$data_options[$field]['data'] = Value::fieldValues($field);
$data_options[$field]['label'] = $options[$field];
if (!in_array($field, ['gender', 'looking_for'])) {
$data_options[$field]['data'][100] = "Doesn't matter";
}
}
//dd($data_options);
return $data_options;
}
If I understand your problem correctly, to deal with multiple checkboxes on PHP you need to add [] to its name property. That way, PHP knows it should interpret theses values as an array.
Also, your input name is not matching with $data[$fieldName].
Do it like this:
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name }}[]" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }} id="{{$name}}-{{ $value }}">
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset

Store registration is not working properly (the code goes always to the else part of the "if ($validator->passes()) {...}"

I have a form in the registration.blade.php page for a user to enter some info to do a registration in a conference.
In the form below there is a part where is used the getHtmlInput() method, that is used to show for each ticket/registration type selected by the user the custom question(s) associated with that registration type for the user to answer. And adds the "required" attribute if in the registration_type_questions pivot table the question has the "required" column as "1".
If the user is doing a registration in a conference and the user didn't select ticket/registration type(s) that have custom questions associated the registration works fine, the code enters in the "if ($validator->passes()) {...}".
Issue:
The issue is when there are custom questions associated with one or more selected ticket/registration types.
If there are custom questions that are required I want to validate that also in Laravel. So I have the code below in the storeRegistration() that shows the message "Fill all mandatory fields" if a custom question that is required was not answered.
But even if the user fill all required custom questions the code never enters in the if "if ($validator->passes()) {...}". Do you know why? Also if the question is required and the required attribute is removed from the HTML in the console and the user click in the "Store Registration" the validation errors don't appear.
The code goes always to the else part of the if " "if ($validator->passes()) {...}" and it shows with "else{dd($validator->errors());}":
MessageBag {#278 ▼
#messages: array:1 [▼
"participant_question.0" => array:1 [▼
0 => "The participant question.0 field is required."
]
]
#format: ":message"
}
Do you know where is the issue?
The storeRegistrationInfo() that stores the registration and has the validation to check if custom question(s) required were not answered:
public function storeRegistration(Request $request, $id, $slug = null, Validator $validator)
{
$user = Auth::user();
$rules = [];
$messages = [];
if (isset($request->participant_question_required)) {
dd($request->participant_question_required);
$messages = [
'participant_question.*.required' => 'Fill all mandatory fields',
];
foreach ($request->participant_question_required as $key => $value) {
$rule = 'string|max:255'; // I think string should come before max
// if this was required, ie 1, prepend "required|" to the rule
if ($value) {
$rule = 'required|' . $rule;
}
$rules["participant_question.{$key}"] = $rule;
}
}
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->passes()) {
dd('test'); // this dont appears
// create an entry in the registrations table
// create an entry in the participants table for each registered participant
// create a entry in the answer table for each answer to a custom question
if (isset($request->participant_question)) {
foreach( $request->participant_question as $key => $question ) {
$answer = Answer::create([
'question_id' => $request->participant_question_id[$key],
'participant_id' => $participants[$key]->id,
'answer' => $request->participant_question[$key],
]);
}
}
}
}
If in the database the questions tables is like:
id question conference_id
1 Phone? 1
And in the database pivot table registration_type_questions is:
id registration_type_id question_id required
1 1 1 1
The generated HTML with the getHTMLInput() based on the values of the pivot table and Questions table above is:
<form method="post" id="registration_form" action="http://proj.test/conference/1/conference-test/registration/storeRegistration">
<input type="hidden" name="_token" value="">
<p> Is not necessary additional info for the registration. Please just answer the following questions. </p>
<input type="hidden" value="" name="participant_name[]">
<input type="hidden" value="" name="participant_surname[]">
<input type="hidden" name="rtypes[]" value="1">
<div class="form-group">
<label for="participant_question">Phone?</label>
<input type="text" name="participant_question" class="form-control" required="">
<input type="hidden" name="participant_question_required[]" value="1">
<input type="hidden" value="1" name="participant_question_id[]">
</div>
<input type="submit" class="btn btn-primary" value="Store Registration">
</form>
The method getHtmlInput() that generates the html is in the Question model:
public function getHtmlInput($name = "", $options = "", $required = false, $class = "", $customtype = false)
{
$html = '';
$html .= $customtype == 'checkbox' ? "<div class='checkbox-group ".($required ? " required" : "")."'>" : '';
$html .= $customtype == 'select_menu' ? "<select name='participant_question' class='form-control' " . ($required ? " required" : "")
. ">" : '';
if (empty($options)) {
switch ($customtype) {
case "text":
$html .= "
<input type='text' name='participant_question' class='form-control'" . ($required ? " required" : "")
. ">";
break;
case "file":
$html .= "
<input type='file' name='participant_question' class='form-control'" . ($required ? " required" : "") . ">";
break;
case "long_text":
$html .= "
<textarea name='participant_question' class='form-control' rows='3'" . ($required ? " required" : "") . ">"
. $name .
"</textarea>";
break;
}
} else {
foreach ($options as $option) {
switch ($customtype) {
case "checkbox":
$html .= "
<div class='form-check'>
<input type='checkbox' name='participant_question[]' value='" . $option->value . "' class='form-check-input' >
<label class='form-check-label' for='exampleCheck1'>" . $option->value . "</label>
</div>";
break;
case "radio_btn":
$html .= "
<div class='form-check'>
<input type='radio' name='participant_question[]' value='" . $option->value . "' class='form-check-input'" . ($required ? " required" : "") . ">" .
' <label class="form-check-label" for="exampleCheck1">' . $option->value . '</label>' .
"</div>";
break;
case "select_menu":
$html .= "<option value='" . $option->value . "'>" . $option->value . "</option>";
break;
}
}
}
$html .= $customtype == 'select_menu' ? "</select>" : '';
$html .= $customtype == 'checkbox' ? "</div>" : '';
return $html;
}
Form in the view that uses the getHtmlInput() to generate the html for the custom questions:
<div class="card-body">
#include('includes.errors')
<form method="post" id="registration_form" action="{{route('conferences.storeRegistration', ['id' => $id, 'slug' => $slug])}}">
{{csrf_field()}}
#if (!is_null($allParticipants) && is_int($allParticipants))
<!-- If all_participants in conferences table is "1"
is necessary to collect the name and surname of all participants -->
#if($allParticipants == 1)
<p>Please fill the following form.</p>
#else
<!-- if is 0 is not necessary to collect the name and surname of each participant
and its used the name and surname of the auth user to do the registration-->
<!-- the registration types selected by the user can have custom questions associated if don't have no
custom question will appear, if 1 or more registration types have custom questions associated they will
appear on the form for the user to answer-->
#if(collect($selectedRtypes)->first()['questions'] == null)
<p>Is not necessary additional info for the registration. </p>
#else
<p>Is not necessary additional info for the registration. Please just answer the following
questions.</p>
#endif
#endif
<!-- for each selected ticket is necessary collect the name and surname because all_participants is "1" inside this if -->
#foreach($selectedRtypes as $k => $selectedRtype)
#foreach(range(1,$selectedRtype['quantity']) as $val)
#if($allParticipants == 1)
<h6 class="text-heading-blue mb-3 pb-2 font-weight-bold">
Participant - {{$val}} - {{$k}}</h6>
<div class="form-group font-size-sm">
<label for="name{{ $k }}_{{ $val }}"
class="text-gray">Name</label>
<input type="text" id="name{{ $k }}_{{ $val }}"
name="participant_name[]" required
class="form-control" value="">
</div>
<div class="form-group font-size-sm">
<label for="surname{{ $k }}_{{ $val }}"
class="text-gray">Surname</label>
<input type="text" id="surname{{ $k }}_{{ $val }}"
required class="form-control"
name="participant_surname[]" value="">
</div>
<!-- for each registration type if there are custom questions thet will appear so the user can answer -->
#foreach($selectedRtype['questions'] as $customQuestion)
<div class="form-group">
<label for="participant_question">{{$customQuestion->question}}</label>
<!--if the custom question is a type checkbox, radio button or select menu-->
#if($customQuestion->hasOptions() && in_array($customQuestion->type, ['checkbox', 'radio_btn', 'select_menu']))
{!! $customQuestion->getHtmlInput(
$customQuestion->name,
$customQuestion->options,
($customQuestion->pivot->required == '1'),
'form-control',
$customQuestion->type)
!!}
<!-- if the custom question is of type text, file, textarea -->
#else
{!! $customQuestion->getHtmlInput(
$customQuestion->name,
[],
($customQuestion->pivot->required == '1'),
'form-control',
$customQuestion->type)
!!}
#endif
<input type="hidden"
name="participant_question_required[]"
value="{{ $customQuestion->pivot->required }}">
<input type="hidden"
value="{{ $customQuestion->id }}"
name="participant_question_id[]"/>
</div>
#endforeach
#else
<input type="hidden" value=""
name="participant_name[]"/>
<input type="hidden" value=""
name="participant_surname[]"/>
#endif
<input type="hidden" name="rtypes[]"
value="{{ $selectedRtype['id'] }}"/>
#endforeach
<!-- is not necessary collect info of each participant and its used the name and surname of the auth user
to do the registration -->
#if ($allParticipants == 0)
<!-- if the selected registration types have custom questions associated they will appear in the form
so the user can answer -->
#foreach($selectedRtype['questions'] as $customQuestion)
<div class="form-group">
<label for="participant_question">{{$customQuestion->question}}</label>
<!-- if the custom question is of type checkbox, radio button or select menu -->
#if($customQuestion->hasOptions() && in_array($customQuestion->type, ['checkbox', 'radio_btn', 'select_menu']))
{!! $customQuestion->getHtmlInput(
$customQuestion->name,
$customQuestion->options,
($customQuestion->pivot->required == '1'),
'form-control',
$customQuestion->type)
!!}
<!-- if the checkbox is of type text, textarea, file-->
#else
{!! $customQuestion->getHtmlInput(
$customQuestion->name,
[],
($customQuestion->pivot->required == '1'),
'form-control',
$customQuestion->type)
!!}
#endif
<input type="hidden"
name="participant_question_required[]"
value="{{ $customQuestion->pivot->required }}">
<input type="hidden"
value="{{ $customQuestion->id }}"
name="participant_question_id[]"/>
</div>
#endforeach
#endif
#endforeach
#endif
<input type="submit" class="btn btn-primary" value="Store Registration"/>
</form>
</div>
$rules before "$validator = Validator::make($request->all(), $rules);" shows:
array:1 [▼
"participant_question.0" => "required|string|max:255"
]
request->all() before "$validator = Validator::make($request->all(), $rules); "shows:
array:7 [▼
"_token" => ""
"participant_name" => array:1 [▼
0 => null
]
"participant_surname" => array:1 [▼
0 => null
]
"rtypes" => array:1 [▼
0 => "1"
]
"participant_question" => "j"
"participant_question_required" => array:1 [▼
0 => "1"
]
"participant_question_id" => array:1 [▼
0 => "1"
]
According to the documentation:
If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
They don't seem to be passing the Validator as a parameter as you are, rather they are statically calling the function without any reference to the request or any other parameters.
Secondly, consider using the nullable validation flag which allows you to define optional fields.
We have a pass method there :
$rules = ['name' => 'unique'];
$input = ['name' => null];
Validator::make($input, $rules)->passes(); // true
So define your rules and number of inputs and give it a go.
You can use dd(Validator::make($input, $rules)->passes();) it will give you true or false, False for not failed validation and true for pass validation.
Further use it like so :
if(Validator::make($input, $rules)->passes(); // true){
//On pass validation, This section will execute
}

Hide an element when a toggle is checked in PHP/Laravel

I am trying to hide an element on my page when I click a toggle and unhide it when I click the toggle again. Here is my HTML code:
<div class="form-group settings-row">
{{ Form::label('notificationSettings', 'Notification Settings', array('class' => 'col-md-2 control-label')) }}
<div class="col-md-10">
<table style="border-width:0; margin-top:4px;">
<tr>
<td>
Notifications Enabled
</td>
<td>
<div class="onoffswitch" style="margin:4px 0 0 7px;">
<input type="checkbox" #if($notificationsEnabled == true)checked #endif name="notifications_toggle" class="onoffswitch-checkbox" id="notifications_toggle">
<label class="onoffswitch-label" for="notifications_toggle">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
</td>
<td></td>
</tr>
</table>
<div class="col-md-10">
#foreach($notificationMessageRadios as $radio)
#if(isset($radio['text']))
<div class="row" style="margin-bottom:1em;">
<input type='radio' name='notificationMessage' id="notificationmessage-other" value="" #if($radio['selected']) checked #endif> {{$radio['message']}}
</div>
<input type="text" id="notificationMessageCustom" placeholder="Pick your own!" #if($radio['selected'])value="{{ $settingsForMessages->notification_message }}" #else value="Pick your own!" #endif name="notificationMessageCustom" class="form-control" #if(!$radio['selected'])style="display:none"#endif>
#else
<div class="row">
<input type='radio' name='notificationMessage' value="{{ $radio['message']}}" #if($radio['selected']) checked #endif> {{ $radio['message'] }}
</div>
#endif
#endforeach
</div>
</div>
</div>
Breakdown:
So when I click the onoffswitch to be on, I want the radios to appear. When I click the onoffswitch to be off, I want the radios to disappear.
I am being thrown into this project, so this code already existed and I am being tasked with editing some features. Any kind of help would be greatly appreciated.
As a bonus, here is the controller side:
$notificationsEnabled = ( $settings['notificationsEnabled'] == 1);
// Cast notification messages to a variable
$notificationMessageMsgs = \Config::get('customer_messages.notificationMessageArray');
$numNotificationMessageMsgs = count($notificationMessageMsgs);
$notificationMessageSelected = false;
// Determine which email subject radio button is checked
foreach($notificationMessageMsgs as $index => $msg) {
$isSelected = false;
if ($settingsForMessages->notification_message == null && $index == 0) {
$notificationMessageSelected = true;
$isSelected = true;
}
if($msg['message'] === $settingsForMessages->notification_message){
$isSelected = true;
$notificationMessageSelected = true;
}
if($index == $numNotificationMessageMsgs - 1 && !$notificationMessageSelected){
$isSelected = true;
}
$notificationMessageRadios[] = array_merge(['selected' => $isSelected], $msg);
}
I am NOT looking for hand holding. I am looking for guidance, that is all.
Maybe try out jQuery?
Try out jQuery Toggle : https://www.w3schools.com/jquery/eff_toggle.asp
$("button").click(function(){
$("p").toggle();
});
This is the code copies from the link . just target your "Class" , "ID" , "element" in the top row $("button") that needs to be clicked and than target the element that needs to be shown/hidden $("p")

Categories