Enumerating elements of a table - php

I have a table and I want to enumerate each element.
Something like this
#foreach($elements as $element)
<tr>
<td>{{ (isset($a))?$a++:($a = 1) }}</td>
<td>...
</tr>
#endforeach
I expect the table to begin with 1 and then count on, however, the first two columns are always 1. I have already solved this problem by giving the template an $a = 0; on the controller but I want to know why my first solution doesn't work and if there is a workaround

Laravel Blade has a very handy variable for loops, called the $loop variable. This lets you gather information about the current element of the list, including the index and iteration count.
So you can do just this:
#foreach($elements as $element)
<tr>
<td>{{ $loop->iteration }}</td>
<td>...
</tr>
#endforeach

Related

Laravel php combine two foreach

In my blade.php file, I'm trying to merge two foreach loop to display data in the table. I had tried use something like nested loop but it doesn't work.
#foreach($cat->products as $idx => $product)
<tr ng-init="item.items[{{$cat->id}}][{{$idx}}] = {};">
#foreach ($queryInv as $querInvs)
<td>{{$product->sku}}</td>
<td>{{$product->name}}</td>
<td class="text-right">{{{$querInvs->total or 0}}}</td>
</tr>
#endforeach
#endforeach
I just need to insert the total data into the table. Now the total is displayed correctly but it will duplicate the sku and name in the table.
Define an array which we will use as a "flag" and on each iteration check if the current product SKU is NOT in our "flag" array. If it isn't then we display and we add the current product SKU to the list of processed SKUs and continue as normal.
#php $skus = [] #endphp
#foreach($cat->products as $idx => $product)
#if (!in_array($product->sku, $skus))
<tr ng-init="item.items[{{$cat->id}}][{{$idx}}] = {};">
#foreach ($queryInv as $querInvs)
<td>{{$product->sku}}</td>
<td>{{$product->name}}</td>
<td class="text-right">{{{$querInvs->total or 0}}}</td>
#endforeach
</tr>
#php array_push($skus, $product->sku); #endphp
#endif
#endforeach
Note: You are using Laravel 4, the current version of Laravel is 5.7, I would absolutely update and use the latest version.
Reading Material
in_array
array_push

Select values from a table where Ids are in json format in another table in laravel

I have a table named journal_details and it has a column named transaction_by_to. I am saving account_head_id values as json_encode format in transaction_by_to in table journal_details. Now I want to run a select query to get account head names from account_heads where transaction_by_to ids in JSON format will find the id from account_heads. In the controller, I tried something like bellow, but it's getting only one. But I want to show all from account_heads for all JSON formatted ids.
public function ledgerSubmit(Request $request)
{
$acId = $request->acount_head;
$startDate = Carbon::parse($request->start_date)->format('Y-m-d');
$endDate = Carbon::parse($request->end_date)->format('Y-m-d');
$reportType = $request->report_type;
$nameOfAccount = AccountHead::find($acId);
$ledgers = DB::table('journal_details')
->join('journals', 'journal_details.journal_id', '=', 'journals.id')
->join('account_heads', 'journal_details.account_head_id', '=', 'account_heads.id')
->where('journal_details.account_head_id', $acId)
->select('journals.number as journalNo', 'journals.journal_date as journalDate', 'journal_details.*', 'account_heads.name as nameOfAccount')
->get();
if (count($ledgers)) {
$transactionByToId = $ledgers[0]->transaction_by_to;
foreach (json_decode($transactionByToId) as $tId) {
$transactionByTo = AccountHead::where('id', $tId)->get();
}
}
return view('report.ledger.searched-result', compact('reportType', 'startDate', 'endDate', 'ledgers', 'transactionByTo', 'nameOfAccount'));
}
And in blade view-
#foreach($ledgers as $ledger)
<tr>
<td>{{ $loop->index + 1 }}</td>
<td>{{ $ledger->journalNo }}</td>
<td>{{ date('jS F, Y', strtotime($ledger->journalDate)) }}</td>
<td>{{ $ledger->nameOfAccount }}</td>
<td>
{{ $transactionByTo[0]->name }}
</td>
<td>
{{ number_format($ledger->debit, 2,".",",") }}
</td>
<td>
{{ number_format($ledger->credit, 2,".",",") }}
</td>
</tr>
#endforeach
["16","17","7","11"] is transaction_by_to column values in json format in journal_details and these ids are id for account_heads table.
There are several errors in your code, like in following code:
foreach (json_decode($transactionByToId) as $tId) {
$transactionByTo = AccountHead::where('id', $tId)->get();
}
it will always keep single value, the last value. So it will seem that there is only one record.
But why don't you do following to get all records at a time:
$accountHeadIds = json_decode($transactionByToId, true);
$accountHeads = AccountHead::whereIn('id', $accountHeadIds)->get();
Secondly, I don't see you are processing Account Head variable (as per my code example, $accountHeads) in the view file that is not part of $leders variable. If you want to have that under $ledgers variable then you should store under it.
Note: I haven't tested the code above, but the concept is similar.

Laravel Eloquent splitting query into array

Bit of a bad title, not quite sure how to research/describe what I'm trying to do.
I have a table called specifications with the fields
id, device_id, name, detail
Two rows for two different devices would for example be
1, 1, weight, 300kg
2, 2, weight, 250kg
Now the way I need to display it is in a single table compare both devices, essentially like this:
#foreach($specifications as $specification)
<tr>
<td>{{ $specification->name }}</td>
<td>{{ $specification->detailOne }}</td>
<td>{{ $specification->detailTwo }}</td>
</tr>
#endforeach
I'm having issues getting the right query or split the query in order to be able to go through the array like above. Anyone mind putting me on the right mindset? Do I query both specs and somehow resort it into an array I can use as above, or is there something else I should be looking at?
This should work for you
#foreach($specifications->groupBy('name') as $name => $specificationGrouped)
<tr>
<td>{{ $name }}</td>
#foreach($specificationGrouped as $specification)
<td>{{ $specification['detail'] }} ({{ $specification['device_id'] }})</td>
#endforeach
</tr>
#endforeach

Accessing Parent Array Names

I have got my App returning this array: http://pastebin.com/3VKcjLMT
I'm trying to list the data on my laravel view as:
FAB0003 - Accessory Stand Short Section
-- MAC0010
-- CUT0010
FAB0004 - Accessory Stand Long Section
-- MAC0011
-- RAW0010
but I can't for the life of me figure out how to access the pieces of information beginning with FAB! My current view code is this:
#foreach ($product->fabrications as $items)
#foreach ($items as $item)
<tr>
<td></td>
<td>{{ $item->part_number }}</td>
</tr>
#endforeach
#endforeach
I would be so grateful if you could help out a PHP noob who has wasted hours on this :(
Try with -
#foreach ($product->fabrications as $key => $items)
$key will be the parent key.
Note : It should be a array key.

How to: foreach without affecting every row?

Is there a way to do a foreach on for example your products and sort this by their category_id and show the category name above the products. (I'm using laravel 4 as framework)
Example what the output should look like:
Chairs
wooden chair number 1
pretty chair number 1
pretty chair number 2
Doors
tall door number 1
white door number 1
Key question: How can i make a foreach without having the categoryname above each row ?
Hopefully i made my question/problem clear and can someone help me out!
This is what i got so far:
Though, when i do my foreach in the blade i will get the error: " Undefined index "
The foreach i used in my controller:
foreach($results as $result) {
$category[$result->category_id][] = $result;
}
My foreach in the blade:
#foreach ($category as $key => $product)
<tr>
<td>{{ $product[$key]['created_at'] }}</td>
<td>{{ $product[$key]['order_id'] }}</td>
<td>{{ $product[$key]['name'] }}</td>
</tr>
#endforeach
you are attempting to use category_id to fetch $product from $products, which is array with 0-X indexes. for sake of simplicity i will ignore html formatting and syntax since i never used framework mentioned...
#foreach ($category as $key => $products)
echo 'Category #', $key
#foreach ($products as $product)
<tr>
<td>{{ $product['created_at'] }}</td>
<td>{{ $product['order_id'] }}</td>
<td>{{ $product['name'] }}</td>
</tr>
#endforeach
#endforeach
not completely sure i understand the question. but if im trying to organize an array.. i might use a conditional statement inside the foreach loop. I'm not sure your question is very clear.. see if this helps at all
foreach($results as $result) {
// just an example.. i narrow down what I push into my category array
if($result->type == 'whatever'){
$category[$result->category_id][] = $result;
}
}

Categories