I have this foreach
foreach ($categoryArr as $key => $value) {
foreach ($biciCorretta as $chiave => $valore) {
$biciSingola = $valore;
$contatoreqty =1;
if ($biciSingola->category_id = $key && $contatoreqty <= $value) {
if (!in_array($biciSingola,$biciSelezionata, true)) {
array_push($biciSelezionata, $biciSingola);
}
$contatoreqty ++;
}
}
echo "$contatoreqty <br>";
}
this is dd $categoryAarr:
array:1 [▼
1 => "1"
]
to be precise
array:1 [▼
1(category id) => "1"(quantity request)
]
this is the dd of $biciCorretta (are the bikes I have in that category):
array:2 [▼
0 => App\Models\Bike {#1461 ▶}
1 => App\Models\Bike {#1459 ▶}
]
if the category of the single bike is correct and the quantity ($ value) is less than or equal to the counter
push the bike into the array.
I expect there is only one bike in the $biciSelezionata array as the quantity required is only one
instead the result is the following:
array:2 [▼
0 => App\Models\Bike {#1461 ▶}
1 => App\Models\Bike {#1459 ▶}
]
there is a problem on your condition
if ($biciSingola->category_id = $key && $contatoreqty <= $value) {
The condition here must be ==
Write if ($biciSingola->category_id == $key && $contatoreqty <= $value) { instead
And its important where you initiate your $contatoreqty variable.
it will always be 1 if condition fails
Related
I'm new to laravel I was trying to get value IN controller form array value compere all "ANSWER" AND "OPTION" array value.
EXAMPLE
ANSWER AND OPTION if
ANSWER 0=>A EQUELS OPTION=>A pass 1
ANSWER 0=>B EQUELS OPTION=>A pass 0
THIS VALUE STORE IN ANSWER_STATUS COLUMANE
CONTROLLER
public function Store_Answer(Request $request)
{
$count= $request->Question;
if ($count) {
for ($i=0; $i <count($request->Question); $i++) {
$data = New OnlineExminAnswer();
$data->ANSWER_STATUS= $request->ANSWER_STATUS; // HERE I WANT TO GET VALUE OF COMPARED 1 OR 0
$data->question = $request->Question [$i];
$data->answer = $request->OPTION[$i];
$data->save();
}
}
my form array
"Question" => array:2 [▼
0 => "YOUR NAME"
1 => "water formula in science"
]
"ANSWER" => array:2 [▼ //THIS ARRAY CONTAINING ALL RIGHT ANSWER
0 => "A"
1 => "h2O"
]
"OPTION" => array:2 [▼ //THIS ARRAY STUDENTS ANSWER
0 => "A"
1 => "CO2"
]
]
public function Store_Answer(Request $request)
{
$count = $request->Question;
if ($count) {
for ($i = 0; $i < count($request->Question); $i++) {
if(isset($request->ANSWER[$i]) && isset($request->OPTION[$i])) {
$data = new OnlineExminAnswer();
$data->ANSWER_STATUS = $request->ANSWER[$i] == $request->OPTION[$i] ? 1 : 0;
$data->question = $request->Question[$i];
$data->answer = $request->OPTION[$i];
$data->save();
}
}
}
}
i have the next collection:
It is grouped by zone and fundo and I need to sum all the sup_ha that each fundo contains
$transporFundo = $tansporCollect->groupBy(['zona','fundo']);
foreach ($transporFundo as $fundo) {
$supFundo = $fundo->sum('sup_ha');
dd($supFundo);
}
that is to say that for example of my collection for zona 1 and fundo 805 I would have to add the sup_ha field of the 364 records that are seen.
I tried to do it but I don't know how to access the field, as seen in my code I tried and it returns 0.
I hope you can help me, thanks
**
UPDATE
**
ok, remove the group by, for example show a collection like the following, the original has 700k of records
Illuminate\Support\Collection {#778646 ▼
#items: array:4 [▼
0 => array:3 [▼
"zona" => 1
"sup_ha" => 20
"fundo" => 805
]
1 => array:3 [▼
"zona" => 1
"sup_ha" => 10
"fundo" => 805
]
2 => array:3 [▼
"zona" => 2
"sup_ha" => 5
"fundo" => 800
]
3 => array:3 [▼
"zona" => 2
"sup_ha" => 10
"fundo" => 900
]
]
}
so, I need the sum of the sup_ha of equal fundo, like this:
fundo | sum
805 | 30
800 | 5
900 | 10
And I need the sum of the sup_ha of equal zona, like this:
zona | sum
1 | 30
2 | 15
Given this, that's why I had made a group by to calculate the sum of the fundo's. so now I don't know whether to think if it was right to do it like this
I hope you have clarified
Assuming your collection is assigned as $collection
$zonaArray = [];
$fundoArray = [];
$sum = 0;
foreach ($collection as $key => $t) {
if (!in_array($t['zona'], $zonaArray)) {
$zonaArray[$key]['zona'] = $t['zona'];
$zonaArray[$key]['sum'] = (float) $t['sup_ha'];
} else {
$zonaArray[$key]['sum'] = (float) $t['sup_ha'];
}
if (!in_array($t['fundo'], $fundoArray)) {
$fundoArray[$key]['fundo'] = $t['fundo'];
$fundoArray[$key]['sum'] = (float) $t['sup_ha'];
} else {
$fundoArray[$key]['sum'] = (float) $t['sup_ha'];
}
}
$checkzona = [];
$value = 0;
$finalZone = [];
$i = 0;
foreach ($zonaArray as $key => $val) {
if (in_array($val['zona'], $checkzona)) {
unset($finalZone[$i - 1]);
$val['sum'] = $value + (float) $val['sum'];
$finalZone[$i] = $val;
$i++;
} else {
$checkzona[] = $val['zona'];
$value = $val['sum'];
$finalZone[$i] = $val;
$i++;
}
}
Your zone wise sum output is looking like below.
array:2 [▼
1 => array:2 [▼
"zona" => 1
"sum" => 30.0
]
3 => array:2 [▼
"zona" => 2
"sum" => 15.0
]
]
For fundo sum:
$checkfundo = [];
$valuefundo = 0;
$finalFundo = [];
$k = 0;
foreach ($fundoArray as $key => $fundo) {
if (in_array($fundo['fundo'], $checkfundo)) {
unset($finalFundo[$k - 1]);
$fundo['sum'] = $valuefundo + (float) $fundo['sum'];
$finalFundo[$k] = $fundo;
$k++;
} else {
$checkfundo[] = $fundo['fundo'];
$valuefundo = $fundo['sum'];
$finalFundo[$k] = $fundo;
$k++;
}
}
Your fundo wise sum output is looking like below.
array:3 [▼
1 => array:2 [▼
"fundo" => 805
"sum" => 30.0
]
2 => array:2 [▼
"fundo" => 800
"sum" => 5.0
]
3 => array:2 [▼
"fundo" => 900
"sum" => 10.0
]
]
I hope it's working for you.
Assuming your collection is assigned to $collection.
so, I need the sum of the sup_ha of equal fundo.
High order functions
return $collection->groupBy('fundo')->map->sum('sup_ha');
Alternative
return $collection
->groupBy('fundo')
->transform(function (Collection $sub) {
return $sub->sum('sup_ha');
});
It prints
{
"805": 30,
"800": 5,
"900": 10
}
And I need the sum of the sup_ha of equal zona
High order functions
return $collection->groupBy('zona')->map->sum('sup_ha');
Alternative
return $collection
->groupBy('zona')
->transform(function (Collection $sub) {
return $sub->sum('sup_ha');
});
It prints
{
"1": 30,
"2": 15
}
I'm creating a collection and using a groupBy to group items together depending on the month, however after this I then want to it to go back to ascending date order (Jan/Feb/Mar). Here is my function that I'm using below;
private function monthByMonthAgentReferrals() {
$case = Case::where('start_date', '>', Carbon::now()->subDays(360))
->where('source', 'AGENT')->get()
->groupBy(function($key) {
return Carbon::parse($key->start_date)->format('m');
});
return $case;
}
At the moment when I display the results I get a return of the months in a random order;
Collection {#1982 ▼
#items: array:12 [▼
12 => Collection {#1321 ▶}
"07" => Collection {#1322 ▶}
10 => Collection {#1320 ▶}
"05" => Collection {#1991 ▶}
"06" => Collection {#1990 ▶}
"08" => Collection {#1989 ▶}
"01" => Collection {#1988 ▶}
11 => Collection {#1987 ▶}
"09" => Collection {#1986 ▶}
"02" => Collection {#1985 ▶}
"03" => Collection {#1984 ▶}
"04" => Collection {#1983 ▶}
]
}
How would I go about sorting by 'start_date' again? or would it be better to sort by the array key? Thanks.
You can use it like this:
$case = Case::where('start_date', '>', Carbon::now()->subDays(360))
->selectRaw('table_name.*')
->where('source', 'AGENT')
->groupBy(function($key) {
return Carbon::parse($key->start_date)->format('m');
})->orderBy('start_date')->get();
private function monthByMonthAgentReferrals() {
$case = Case::where('start_date', '>', Carbon::now()->subDays(360))
->where('source', 'AGENT')->get()
->groupBy(function($key) {
return Carbon::parse($key->start_date)->format('m');
})->toArray();
ksort($case);
return collect($case);
}
Converts the collection to an array, use the function ksort on the array and then recollect the array.
I have a collection with 4 Object :
Collection{#645 ▼
#items: array:4 [▼
0 => Team {#644 ▶}
1 => Team {#613 ▶}
2 => Team {#607 ▶}
3 => Team {#599 ▶}
]
}
I would like to insert a element each 3, begining by 0 index ( In this case, it would be in 0, and 3)
How should I do it???
The push method doesn't allow me to insert between to elements....
Use the map() helper. I've tested this and it works perfectly:
$counter = 0;
$collection->map(function($i) use(&$counter) {
if ($counter % 3 === 0) {
$i->custom = 'Custom value';
}
$counter++;
return $i;
});
I'm using Laravel 5.2, and as documentation says:
boolean
The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".
So I've created a checkbox (styled like a switch from materialize), to return true when on, and false when off. Here goes the blade:
{!! Form::hidden('eh_capa', 0) !!}
Want to select as a graph cover?
<label>
Off
<input name="cover" type="checkbox" checked>
<span class="lever"></span>
on
</label>
Of course this code goes inside a form tag. I do the validation inside a Request class as said on this part of laravel documentation, here is my rules method:
public function rules()
{
$this['cover'] = $this['cover'] === 'on' ? 1 : 0;
$this['obra_id'] = $this->route('obra');
$this['arquivo'] = $this->hasFile('arquivo') ? $this->file('arquivo') : NULL;
dd($this);
return [
'cover' => 'required|boolean',
'obra_id' => 'exists:obras',
'path' => 'required',
'arquivo' => 'required|file|max:2048|mimes:pdf',
];
}
The dd() function returns my request like this:
StoreGraficoPostRequest {#441 ▼
#container: Application {#3 ▶}
#redirector: Redirector {#448 ▶}
#redirect: null
#redirectRoute: null
#redirectAction: null
#errorBag: "default"
#dontFlash: array:2 [▶]
#json: null
#convertedFiles: array:1 [▶]
#userResolver: Closure {#355 ▶}
#routeResolver: Closure {#354 ▶}
+attributes: ParameterBag {#443 ▶}
+request: ParameterBag {#440 ▼
#parameters: array:5 [▼
"_token" => "bZIpGW6UCcYHlCTZuIZMtmOrpCodWyfcbO1HgQid"
"path" => "hello.pdf"
"cover" => 1
"obra_id" => "29"
"arquivo" => UploadedFile {#438 ▶}
]
}
+query: ParameterBag {#442 ▶}
+server: ServerBag {#446 ▶}
+files: FileBag {#445 ▶}
+cookies: ParameterBag {#444 ▶}
+headers: HeaderBag {#447 ▶}
#content: ""
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: null
#requestUri: null
#baseUrl: null
#basePath: null
#method: "POST"
#format: null
#session: Store {#394 ▶}
#locale: null
#defaultLocale: "en"
}
But when I comment the dd function, the validation returns that cover must be true or false. The same happens if I change the value of cover field to true, "1" and "true" when on. I've searched all the web for anything that helps and got nothing... I'm beginning to think that this is a Laravel bug...
Well, I got a way to do it. The trick was just to add this code to my Request class:
protected function getValidatorInstance()
{
$data = $this->all();
$data['eh_capa'] = $data['eh_capa'] === 'on' ? 1 : 0;
$data['obra_id'] = $this->route('obra');
$this->getInputSource()->replace($data);
/* modify data before send to validator */
return parent::getValidatorInstance();
}
and then, my rules method ended only with the return.
You are modifying your input in the wrong place. You should override the all() function in your request class, and modify your input there.
public function rules()
{
return [
'cover' => 'required|boolean',
'obra_id' => 'exists:obras',
'path' => 'required',
'arquivo' => 'required|file|max:2048|mimes:pdf',
];
}
public function all()
{
$input = parent::all();
$input['cover'] = $input['cover'] === 'on' ? 1 : 0;
$input['obra_id'] = ...
$input['arquivo'] = ...
return $input;
}
I ran into the same problem and decided to create a small static class that parses all values that are marked as boolean in a rule.
The advantage is that it will only parse booleans that the rules dictate to be boolean. Any other input values will go unchanged, making it still possible to post a string with value 'true' if you desire.
<?php
namespace App\Helpers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ValidationHelper {
/**
* A recursive funciton to loop over any input and parse them to true booleans.
*/
private static function _getObj(&$inputs, $idPath) {
$idPart = array_shift($idPath);
if (count($idPath) > 0) {
if ($idPart == '*') {
for ($i = 0; $i < count($inputs); $i++) {
ValidationHelper::_getObj($inputs[$i], $idPath);
}
}
else {
ValidationHelper::_getObj($inputs[$idPart], $idPath);
}
}
else {
$currentValue = $inputs[$idPart];
if ($currentValue == 1 || strtolower($currentValue) == 'true') {
$inputs[$idPart] = true;
}
else if ($currentValue == 0 || strtolower($currentValue) == 'false') {
$inputs[$idPart] = false;
}
else { // any other value will be left untouched
$inputs[$idPart] = $currentValue;
}
}
}
/**
* Will validate a request against the given rules.
* Will also help fix any booleans that otherwise are parsed as 'true' strings.
* #param Request $request
* #param Array $rules
* #return void
*/
public static function validateRequest(Request $request, $rules) {
// Find any rules demanding booleans:
$booleanIDs = [];
foreach ($rules as $id => $rule) {
if (is_string($rule)) {
$rule = explode('|', $rule);
}
if (in_array('boolean', $rule)) {
$booleanIDs[] = $id;
}
}
if (isset($booleanIDs)) {
// Set all inputs to a bindable array:
$inputs = [];
foreach ($request->all() as $key => $value) {
$inputs[$key] = $value;
}
// Recursively loop through the boolean-ids
foreach ($booleanIDs as $id) {
$idPath = explode('.', $id);
ValidationHelper::_getObj($inputs, $idPath);
}
// Make sure the booleans are not just validated correctly but also stay cast when accessing them through the $request later on.
$request->replace($inputs);
}
else {
$inputs = $request->all();
}
$validator = Validator::make($inputs, $rules);
if ($validator->fails()) {
throw new \Exception('INVALID_ARGUMENTS', $validator->errors()->all());
}
}
}
Rules can be set as array or string (as normal) and it even works with nested values:
ValidationHelper::validateRequest($request, [
['foo'] => ['nullable', 'boolean'],
['bar'] => ['required', 'boolean'],
['item.*.isFoo'] => ['nullable', 'boolean'],
['item.*.isBar'] => 'required|boolean'],
]);