Laravel, get id on request from input blade - php

I have many <input> like this:
<input type="number" id="{!! $item->id !!}" name="function_count[]" value="{{ $item->value }}"
In Controller, I can get an array of each input value, with:
$inputs = $request->input('function_count');
But also I need to get the id="{!! $item->id !!}" in the same array, because I need the data related (id and value) in the Controller. How could I do that?

You cannot pass two values via one input field. However, to achieve what you want, you can have different approaches.
Recommended Approach:
I am assuming, your function_count[] hasMany id. Therefore, you can create associative array as your input name like this:
<input type="number" name="function_count[{!! $item->id !!}]" value="" />
Later you can,
$inputs = $request->input('function_count');
foreach($inputs as $id=>$value){
// $id being the content of $item->id
// $value being the content of value=""
}
Approach #2:
If your id="{!! $item->id !!}" has client-side importance and you want to keep the attribute, you can also combine the data right before the form is submitted like this:
$("form").submit( function () {
$(this).find("input[type=number]").each(function(){
$(this).val($(this).attr("id") + ":" + $(this).val());
});
return;
});
Later you can,
$inputs = $request->input('function_count');
foreach($inputs as $input){
$contents = explode(":",$input);
// $contents[0] being the content of $item->id
// $contents[1] being the content of value=""
}

Related

how to Concatenate an id in a foreach loop using jquery laravel

i have a foreach loop whereby i want to concatenate the id of each loop to its id jquery.i have tried this but i get the the id for the first loop only.this is my code in the blade file.
#foreach ($rentalcategories as $category)
<div class="checkbox checkbox-success">
<input type="text" value="{{ $category->id }}" class="catid">
<input type="radio" name="rentalcategory" class="rentalcattitle" id="rentalcat{{ $category->id }}" value="{{ $category->id }}">
<label for="rentalcat" class="control-label"> {{ $category->rentalcat_title }}</label><span>({{ $category->rentalhses->count() }})</span>
</div>
#endforeach
this is my jquery code
var categoryid=$(".catid").val();
console.log(categoryid);
var hsecategory= $('#rentalcat' + categoryid).prop('checked') ? $('#rentalcat' + categoryid).value : ''
on the console logging the categoryid variable am only getting the first value only for the first loop but the other one it doesn't show.how can i get the id for each loop then concatenate to an id in each loop.
here in my code i want to get the value for each loop using the id instead of class.how can i achieve this
I think because the Id as incrementing within the loop you just need to find element by id that starts with rentalcat
so something like this
$('input[id^="rentalcat"]')
credit to : Find html element which id starts with
that should give all the instances so you will need to preform an each function to get out each instance value
$('input[id^="rentalcat"]').each(function( i ) {
console.log($(this).val())
});
you can then concatenate that values or do whatever you need with the id's in the each loop
I hope this helps

Laravel: How to get the value from the checkbox along with the value from the text input

I have input id and ballance, id as check box and ballance as text input. I want when the id is checked, the ballance request matches the id that was checked. but at this time all ballance entered into request. How to solve the problem from front-end & back-end?
My view:
My view code:
<th>
<div>
<input name="id[]" value="{{$item->id}}" type="checkbox"> <label class="" for="{{$item->id}}"></label>
</div>
</th>
<td> {{ $item->id }} </td>
<td>
<input type="text" class="form-control form-control-sm txtInt saldoChild" name="ballance[]" size="1" id="{{$item->id}}" value="0">
</td>
My return of request:
My backend:
public function store(Request $request)
{
return $request;
}
Thanks..
when an input in html is disabled, the value of that wont send to controller.
so try this:
<script>
$('input[type="checkbox"]').on("change", function(){
if($(this).is(":checked")){
$(this).closest('tr').find('.saldoChild').prop("disabled",false); //Enable the textBox
}
else{
$(this).closest('tr').find('.saldoChild').prop("disabled",true); //Disable the textbox
}
});
</script>
and at the page loading you have to Disable All input type text, that the checkbox of this tr is unchecked.
easiest way is that you have your balance array. so you can get those value who are not 0 and push them to new array and then you are good to go!
first index of id array is for first index of your new array. you can store them in another array or in db

Retrieving and passing data to form input

I have two DB tables as item and price.
In view file, foreach of items I have form element as
<input type="text" name="dc_{{$item->id}}" value="{{$price->dc_*}}">
I want * in value as dc_{{$item->id}} for an example like dc_4 or dc_7
I am unable to use {{ $price-> dc_{{$item->id}} }} for value as it is wrong syntax.
What's an alternative way to implement such logic?
You can do
<input type="text" name="dc_{{ $item->id }}" value="{{ $price->{ 'dc_' . $item->id } }}">

Why is my form only passing input data from last field within foreach loop to database?

I am trying to update some data in my database from a form with this foreach loop:
$players_ids = $_POST['player_ids'];
foreach($players_ids as $player_id) {
foreach($_POST['goals'] as $goals) {
var_dump($goals);
$updateGoals = \DB::table('stats')->where('id', $player_id)->update(['goals' => $goals]);
}
foreach($_POST['assists'] as $assists) {
var_dump($assists);
$updateAssists = \DB::table('stats')->where('id', $player_id)->update(['assists' => $assists]);
}
foreach($_POST['tackles'] as $tackles) {
var_dump($tackles);
$updateTackles = \DB::table('stats')->where('id', $player_id)->update(['tackles' => $tackles]);
}
}
Here is the form:
#foreach($players as $player)
<tr>
<input type="hidden" name="player_ids[]" value="{{ $player->id }}">
<input type="hidden" name="game_id" value="{{ $game->id }}">
<td>{{ $player->fn }} {{ $player->ln }}</td>
<td><input type="number" value="0" name="goals[]" placeholder="goals"></td>
<td><input type="number" value="0" name="assists[]" placeholder="assists"></td>
<td><input type="number" value="0" name="tackles[]" placeholder="tackles"></td>
</tr>
#endforeach
When I try to submit this data, instead of passing through the individual stats of each player to the database, it only passes through the data of the last player in the foreach loop to every player. So if the final player has 3 goals, everyone will get 3 goals in the database. This is obviously not how I would like this to function.
I know soon after this I will run into an issue with updating the data in my database, because I'm not looking to override what is already in the database, but instead add the value passed through to the value already in the database, so if anyone has any knowledge on that as well would be greatly appreciated.
Your form has multiple copies of elements with the same name. Due to this, it only uses the last element with that name.
To utilize an array of values, you will need to use [] like you did for player_ids.
The reason this is happening is you are updating each player with the very last value set for goals, assists, and tackles. (Actually you are updating each player with every set for goals, assists and tackles, resulting in many queries.) You might need to change up your inputs so you know exactly what to update each player with.
This will also result in less looping and fewer queries.
#foreach($players as $player)
<tr>
<input type="hidden" name="player_ids[]" value="{{ $player->id }}">
<input type="hidden" name="game_id" value="{{ $game->id }}">
<td>{{ $player->fn }} {{ $player->ln }}</td>
<td><input type="number" value="0" name="goals[{{ $player->id }}]" placeholder="goals"></td>
<td><input type="number" value="0" name="assists[{{ $player->id }}]" placeholder="assists"></td>
<td><input type="number" value="0" name="tackles[{{ $player->id }}]" placeholder="tackles"></td>
</tr>
#endforeach
$players_ids = $_POST['player_ids'];
foreach ($players_ids as $player_id) {
$updates = \DB::table('stats')->where('id', $player_id)->update([
'goals' => $_POST['goals'][$player_id],
'assists' => $_POST['assists'][$player_id],
'tackles' => $_POST['tackles'][$player_id]
]);
}
This is untested, but if you want it to be additive in your database and not overwrite past values, you might be able to do something like this...
$players_ids = $_POST['player_ids'];
foreach($players_ids as $player_id) {
$updates = \DB::table('stats')->where('id', $player_id)->update([
'goals' => $_POST['goals'][$player_id] . '+' . DB::raw('goals'),
'assists' => $_POST['assists'][$player_id] . '+' . DB::raw('assists'),
'tackles' => $_POST['tackles'][$player_id] . '+' . DB::raw('tackles')
]);
}
Generally a better route would be to not make them additive though, and then you'd just use sum() to figure out how many goals, tackles, and assists each player has. Then you'd be able to do additional filtering on that like goals by date, goals by game, etc...

Looping through input array in Laravel 5

I have a basic UI where users can add a simple list with a label and a value. I want to loop through that list to store the data in a "Detail" model.
I have the following code.
Controller:
$details = $request->input('detail_label');
foreach($details as $key => $value)
{
if(!empty($request->input('detail_value.'.$key))) {
// if the detail has an existing ID
if($request->input('detail_id.'.$key)) {
$detail = Detail::find($request->input('detail_id.'.$key));
} else {
$detail = new Detail;
}
$detail->type = $request->input('detail_type.'.$key);
$detail->label = $request->input('detail_label.'.$key);
$detail->value = $request->input('detail_value.'.$key);
if($request->input('detail_privacy.'.$key) == 1) {
$detail->privacy = 1;
} else {
$detail->privacy = 0;
}
$user->details()->save($detail);
}
}
View:
#foreach($user->details as $detail)
<div class="detail">
<input type="hidden" name="detail_id[]" value="{{ $detail->id }}">
<label>Type
<select name="detail_type[]">
<option #if($detail->type == '1')selected #endif value="1">Phone</option>
<option #if($detail->type == '2')selected #endif value="2">Phone (mobile)</option>
<option #if($detail->type == '3')selected #endif value="3">URL</option>
<option #if($detail->type == '4')selected #endif value="4">Email</option>
</select>
</label>
<label>Label
<input type="text" name="detail_label[]" value="{{ $detail->label }}">
</label>
<label>Value
<input type="text" name="detail_value[]" value="{{ $detail->value }}">
</label>
<label>Private?
<input type="checkbox" name="detail_privacy[]" #if($detail->privacy == true) checked #endif value="1">
</label>
<label>Delete?
<input type="checkbox" name="detail_delete[]" value="{{ $detail->id }}">
</label>
</div><!-- / detail -->
#endforeach
Every aspect of my code works as I had planned except the detail_privacy field. It sets and unsets the boolean privacy attribute but it pays no attention to which $key I want. It always sets it according to the order in the loop. If I just set one detail to be private it will be first. If I set two, (whichever two), it will be the first and second.
Something is clearly wrong with my logic but I can't tell what.
Any help would be really appreciated. Thanks!
The reason it doesn't work is that non-checked checkboxes are not included in the post data. You may see it by dumping value of $request->input('detail_privacy').
To be able both to edit existing and add new details, you need to set keys on inputs in the form. Anything really, as long as you keep track of it. To make things easier you can add hidden input named same as the checkbox, so detail_privacy will be always present in the post data. For example:
#foreach ($user->details as $key => $detail)
<input type="hidden" name="detail_id[{{ $key }}]" value="{{ $detail->id }}">
...
<input type="hidden" name="detail_privacy[{{ $key }}]" value="0">
<input type="checkbox" name="detail_privacy[{{ $key }}]" #if($detail->privacy == true) checked #endif value="1">
...
#endforeach
If you add new fields dynamically ie. with javascript you need to respect those keys. Its quite simple though, just pass last value of $key to your js and you're set.
Also I would recommend different notation for input names: details[{{ $key }}][id] instead of detail_id[{{ $key }}]. This way controller action will become much simpler:
foreach ($details as $detail) {
if (! empty($detail['id'])) {
...
}
}
If the Boolean values are stored as TINYINTS in the Database (as in: 0 or 1); then perhaps taking out the Boolean true || false may resolve the Issue. Not Certain but guessing it's worth the try:
<!-- JUST TRY IT LIKE SO: #if($detail->privacy) checked #endif -->
<label>Private?
<input type="checkbox"
name="detail_privacy[]"
#if($detail->privacy) checked #endif value="1"
>
</label>
Or Hypothetically:
<!-- YOU MAY ALSO USE "1" LIKE SO: #if($detail->privacy==1) checked #endif -->
<label>Private?
<input type="checkbox"
name="detail_privacy[]"
#if($detail->privacy==1) checked #endif value="1"
>
</label>

Categories