Reputation: 3910
I am using the @each blade directive to loop through an array of query results and render them (in this case, the @each directive tends to be a bit of a better idea than a foreach loop since the HTML that will be renders changes depending on the result of the query). This all works fine, but I have the issue of trying to get the current index of the query itself.
In other words, using the @each directive, I need to be able to access the key (or index) of the current loop in the partial that is being rendered.
If you have anything that you need to know, just ask.
Thank you for reading!
Upvotes: 2
Views: 1616
Reputation: 11971
Looking at the source code that's run for the @each
directive yields the following:
Illuminate\View\Factory.php
/**
* Get the rendered contents of a partial from a loop.
*
* @param string $view
* @param array $data
* @param string $iterator
* @param string $empty
* @return string
*/
public function renderEach($view, $data, $iterator, $empty = 'raw|')
{
$result = '';
// If is actually data in the array, we will loop through the data and append
// an instance of the partial view to the final result HTML passing in the
// iterated value of this data array, allowing the views to access them.
if (count($data) > 0) {
foreach ($data as $key => $value) {
$data = ['key' => $key, $iterator => $value];
$result .= $this->make($view, $data)->render();
}
}
// If there is no data in the array, we will render the contents of the empty
// view. Alternatively, the "empty view" could be a raw string that begins
// with "raw|" for convenience and to let this know that it is a string.
else {
if (Str::startsWith($empty, 'raw|')) {
$result = substr($empty, 4);
} else {
$result = $this->make($empty)->render();
}
}
return $result;
}
If you notice on these lines:
$data = ['key' => $key, $iterator => $value];
$result .= $this->make($view, $data)->render();
A variable called $key
is automatically passed to the rendered view. That should contain the current index of your array loop.
Upvotes: 6