Output Laravel collection in groups of two - php

I'm struggling to split the table into two columns in Laravel blade. For example if I have 17 rows, I want to display 9 of them in first column, and the rest in the second. This is my code:
#foreach($idAndProducts as $id)
<tr>
<td width="15px">
<input type="checkbox" id="products{{$id->product_id}}" name="products[]" value="{{$id->product_id}}">
<input type="hidden" name="campaignID[]" value="{{$id->id}}"></td>
<td width="480px"><label for="products{{$id->product_id}}">{{$id->products}}</label></td>
</tr>
#endforeach
Is there a way to do this within a Blade or using jQuery?

You can use array_chunk to split them into groups of two. Try this:
#foreach ( array_chunk($idAndProducts, 2) as $row )
<tr>
#foreach ( $row as $id )
<td width="15px">
<input type="checkbox" id="products{{$id->product_id}}" name="products[]" value="{{$id->product_id}}">
<input type="hidden" name="campaignID[]" value="{{$id->id}}">
</td>
<td width="480px">
<label for="products{{$id->product_id}}">{{$id->products}}</label>
</td>
#endforeach
</tr>
#endforeach
Please note that if $idAndProducts is a collection then array_chunk will not work. You will need to use the inbuilt method chunk instead. Just update the first line to read
#foreach ( $idAndProducts->chunk(2) as $row )

Related

For each problems Laravel Blade

Hi I'd like to ask if my query is correct.
#foreach ($indemnity_benefits->where(['indemnity_benefit_type' => 'Ee', 'indemnity_benefit_group' => 'Basic Benefits'])->get() as $key => $benefit)
<tr>
<td>
<input type="hidden" name="bBenefitEeDesc[]" value="{{$benefit->indemnity_benefit_desc}}">
<span class="p-2">{{$benefit->indemnity_benefit_desc}}</span>
</td>
<td><input style="width: 75px;" name="bBenefitEeMaxDays[]" value="{{old('bBenefitEeMaxDays.'.$key, $benefit->indemnity_benefit_maxdays)}}" class="form-control form-control-sm"></td>
{{-- #for ($index = 0; $index < $noOfCols; $index++)
<td><input name="bBenefitEeValue{{$key}}[]" value="{{old('bBenefitEeValue'.$key.'.'.$index, '')}}" type="text" class="form-control form-control-sm"></td>
#endfor --}}
#foreach ($indemnity_values->where('indemnity_benefit_id', $benefit->id)->get() as $item)
<td><input name="" value="{{$item->indemnity_benefit_value}}" type="text" class="form-control form-control-sm"></td>
#endforeach
</tr>
#endforeach
When I put $benefit->id in the second for each only one row with columns appear. Something like this.
Here are the queries:
$sob_indemnity = SobGhIndemnityComprehensive::where('rfq_version_id', $rfq_version_id)->where('type', 'Indemnity')->first();
//Indemnity Levels
$sob_indemnity_levels = SobghIndemnityLevel::where('sob_gh_ind_comp_id', $sob_indemnity->id);
$indemnity_benefits = SobghIndemnityBenefit::where('sob_gh_ind_comp_id', $sob_indemnity->id);
$indemnity_values = SobghIndemnityBenefitsValue::where('sob_gh_ind_comp_id', $sob_indemnity->id);
Your $indemnity_values is a mutable object, so on your first line you are calling:
$indemnity_values
->where('indemnity_benefit_id', 1)
->get()
And on your second line you are calling the following that is obviously returning an empty collection.
$indemnity_values
->where('indemnity_benefit_id', 1)
->where('indemnity_benefit_id', 2)
->get()
you need to clone your query:
#foreach ((clone $indemnity_values)->where('indemnity_benefit_id', $benefit->id)->get() as $item)

Laravel Inserting Data Only the Last List or Data

I want to insert the data specifically look at my page.
When I set time the data will be inserted. But what I have right now is the data that is inserted is the very last data on this table which is January-31-2019 how can I fix it so when I insert data, the data will insert any of the data that is list on the table.
Controller
public function insertSchedule(Request $request)
{
$employeeTimeSet = new Schedule;
$employeeTimeSet->employee_no = $request->input('hidEmployeeno');
$employeeTimeSet->last_name = $request->input('hidEmployeeLast');
$employeeTimeSet->first_name = $request->input('hidEmployeeFirst');
$employeeTimeSet->date_today = $request->input('dateToday');
$employeeTimeSet->time_in = $request->input('timeIn');
$employeeTimeSet->time_out = $request->input('timeOut');
$employeeTimeSet->save();
$notification = array(
'message' => 'Click PLAN TIME! Employee Time Set!',
'alert-type' => 'success'
);
return redirect()->back()->with($notification, 'Employee Time Set');
}
View
{!! Form::open(['action' => 'Admin\EmployeeFilemController#insertSchedule', 'method' => 'POST']) !!}
<div class="row">
<div class="form-group col-md-12">
<small>Employee No. and Name:</small>
<b><i> {{ $employee->employee_no }} : {{ $employee->last_name }}, {{ $employee->first_name }}</i></b>
<input type="hidden" name="hidEmployeeno" value='<?php echo $employee->employee_no ?>'>
<input type="hidden" name="hidEmployeeLast" value='<?php echo $employee->last_name ?>'>
<input type="hidden" name="hidEmployeeFirst" value='<?php echo $employee->first_name ?>'>
<hr>
</div>
</div>
#php
$today = today();
$dates = [];
for($i=1; $i < $today->daysInMonth + 1; ++$i) {
$dates[] = \Carbon\Carbon::createFromDate($today->year, $today->month, $i)->format('F-d-Y');
}
#endphp
<table class="table">
<thead>
<tr>
<th>DATE TODAY</th>
<th>TIME IN</th>
<th>TIME OUT</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
#foreach($dates as $date)
<tr>
<td><b>{{ $date }}</b></td>
<input type="hidden" name="dateToday" value="{{ $date }}">
<td><input type="time" name="timeIn" class="form-control col-md-10"></td>
<td><input type="time" name="timeOut" class="form-control col-md-10"></td>
<td> {{Form::button('<i class="fa fa-clock"> SET TIME</i>',['type' => 'submit','class' => 'btn btn-warning btn-sm', 'style'=>"display: inline-block;"])}}</td>
</tr>
#endforeach
</tbody>
</table>
{!! Form::close() !!}
The issue is that you are using one form with multiple inputs in it and there is no unique name to them. If you inspect the code, your form will have 31 inputs with name timeIn and 31 inputs with name timeOut.
When you submit the form, It picks the last timeIn and timeOut.
Two soluctions
Make multiple forms (put form tags in while loop, it will create 31 forms in the page)
Use ajax to send data to the server.
You need to use [] for your textbox names. Example : name[] and you need to use a loop to post it. Example - how to get post from same name textboxes in php
In Addition to the #Swaroop's Answer there is another option. You can make array of these fields in the same form and submit them. and at the server end, you will have to loop through posted array so that you can process them further.

Wrong checked checkbox Angularjs

I have a problem with a template with AngularJS.
The page shows a books list with a checkbox. This is used for batch actions, like delete the books. If the list is too long, the books will be shown in a paged list
The problem is, if I check some of them and change the page number, the checkbox will be checked in the same position.
Is easier to understan with this screenshots
I check the first and the third result:
https://i.stack.imgur.com/NK5jE.jpg
Click on the next page:
https://i.stack.imgur.com/GEuMc.jpg
Distinct pages and results, same checked checkbox
The get this results I´m using a query in a action.class.php and sending the json like this:
$ejemplares = array();
foreach($data as $ejemplar_bd)
{
$id_documento = $ejemplar_bd['id_registro'];
$ejemplar = array();
$ejemplar['id'] = $ejemplar_bd['id'];
$ejemplar['idDoc'] = (int)$ejemplar_bd['id_registro'];
$ejemplar['numregistro'] = (int)$ejemplar_bd['numregistro'];
$ejemplar['codigo'] = $ejemplar_bd['codigoejemplar'];
$ejemplar['estado'] = $ejemplar_bd['estado'];
$ejemplar['signatura'] = $ejemplar_bd['signatura1']."-".$ejemplar_bd['signatura2']."-".$ejemplar_bd['signatura3'];
$ejemplar['tipo'] =$ejemplar_bd['tipoejemplar'];
$ejemplar['reservas']=$ejemplar_bd['reservas'];
$ejemplar['Ubicacion']=$ubicaciones[$ejemplar_bd['id']];
$ejemplar['Motivo']=$ejemplar_bd['motivo_expurgado'];
$ejemplar['Editorial']=$data_editorial['valor'];
$ejemplar['Imprimido']= $ejemplar_bd['imprimido'];
$ejemplar = array_merge($ejemplar,$fondos[$id_documento][$ejemplar['id']]);
$ejemplares[] = $ejemplar;
}
$this->json_data = json_encode($ejemplares);
After that, the code in the template is:
<tr ng-repeat="item in data| filter:Buscar | filtroNumregistro:numregistro | filtroCodEjemplar:codEjemplar | filtroNombreNormalizado:nombreFiltro | orderBy:sort:reverse | limitTo: (currentPage - 1) * pageSize - filtrados.length | limitTo: pageSize track by $index">
<td class="sf_admin_text sf_admin_list_td_nombre">
<input type="checkbox" name="ids[]" value="{{ item.id }}" class="sf_admin_batch_checkbox">
</td>
<td class="sf_admin_text">
{{ item.codigo }}
</td>
<td class="sf_admin_text">
{{ item.numregistro }}
</td>
<td class="sf_admin_text sf_admin_list_td_titulo">
<span><a ng-href="{{cambiarUrlTitulo(item.id)}}">{{ item.Titulo }}</a></span><br/>
<span class="autorListEjemplar" ng-repeat="autor in item.Autor">{{autor}}{{$last ? '' : ' - '}}</span>
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.ISBN }}
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.Editorial }}
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.Ubicacion }}
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.signatura }}
</td>
<td class="sf_admin_text">
{{ item.tipo }}
</td>
</tr> etc...
What is going on?
What could be the problem?
Thanks in advance
I have to replace:
<input type="checkbox" name="ids[]" value="{{ item.id }}" class="sf_admin_batch_checkbox">
for
<input type="checkbox" ng-model="item.checked" class="sf_admin_batch_checkbox">

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...

Retrieve a variable whos name is has another variable in it

Dunno if the title makes sense, but I have a variable which would to put it in basic terms would be called like this:
$_POST['something'+$variable2]
I have a form which is for editing selected records, this form contains entries for all previously selected records:
<form name="input" action="editcar.php" method="POST">
<input type="submit" value="Yes">
while($row = mysqli_fetch_assoc($result))
{
echo'
</div>
<table style="color:white">
<tr>
<td style="text-align:right">Manufacture:</td><td><input type="text" name="manufacture'.$row['carIndex'].'" value="'.$row['make'].'"></td>
<td style="text-align:right">Model: </td><td><input type="text" name="model'.$row['carIndex'].'" value="'.$row['model'].'"></td>
</tr>
<tr>
<td style="text-align:right">Colour: </td><td><input type="text" name="colour'.$row['carIndex'].'" value="'.$row['colour'].'"></td>
<td style="text-align:right">Reg: </td><td><input type="text" name="reg'.$row['carIndex'].'" value="'.$row['Reg'].'"></td>
</tr>
<tr>
<td style="text-align:right">Price: </td><td><input type="text" name="price'.$row['carIndex'].'" value="'.$row['price'].'"></td>
<td style="text-align:right">Mileage: </td><td><input type="text" name="mileage'.$row['carIndex'].'" value="'.$row['miles'].'"></td>
</tr>
<tr>
<td style="text-align:right">Max MPH: </td><td><input type="text" name="mph'.$row['carIndex'].'" value="'.$row['mph'].'"></td>
<td style="text-align:right">MPG: </td><td><input type="text" name="mpg'.$row['carIndex'].'" value="'.$row['mpg'].'"></td>
</tr>
</table>
</form>
</div> ';
}
?>
</form>
The form is looped for each record previously chosen, to enable mass editing. The isue arouses when I realised I'd have multiple inputs with the same name, so I did:
<input type="text" name="model'.$row['carIndex'].'" value="'.$row['model'].'">
Placing the primary key of the record it was currently tired to on the end of it's name. Which seemed like a logical way to go about things.
However now I need to call these variables to place in the mysql query and I dunno how to do that, or even if I can.
I have the selected records saved in an array so I have:
foreach ($postid as $carID)
{
$query = "stuff";
mysqli_query($db, $query);
}
Each loop has $carID containing the variables that was put on the end of the form input names.
So something like:
$_POST['something'+$variable2]
is all I can think of but doesn't work.
Any method that works for my overall code is welcome not just a solution to the issue I've made.
Actually your way should work. Just replace the + with . in $_POST['something'+$variable2].
My tip is: use an array as name in your html instead:
<input type="text" name="model[]" value="'.$row['model'].'">
On php-Side you can loop through all $_POST['model'] since its an array now.
You can add the index for every entry in your html, too:
<input type="text" name="model['.$row['carIndex'].']" value="'.$row['model'].'">
PHP uses a dot for concatenation, not + like Java and Javascript:
$_POST['something' . $variable2]
Try something like this:
<form ...>
<?php
while($row = mysqli_fetch_assoc(...):
$index = $row['carIndex'];
?>
<input type="text" name="carmodel[<?php echo $index?>][model]" value="<?php echo $row['model'] ?>">
<?php endforeach; ?>
</form>
This way you will have the data stored in $_POST['carmodel'] as an array indexed by carIndex value as the structure of data in $_POST is defined by names of inputs, here you will have names likee carmodel[1][model] for example so then in post it will be in $_POST['carmodel'][1][model]
you can read here as well
How would I create this array structure in an HTML form?

Categories