2

我正在将 Laravel 从 5.2 升级到 5.3,并且我的 Blade 视图之一不再工作。我将一个数组传递给包含的视图以循环遍历它。我正在使用该forelse指令,但它一直给我一个 Undefined offset: 1 错误。

这是带有视图调用的控制器片段:

$transactions = $committees->transactions()
    ->where('FiledDate', '<=', $to)  // Upper date
    ->where('FiledDate', '>=', $from)  // Lower date
    ->get();

return view('committees.show',
    [ 
        'data' => $data,
        'transactions' => $transactions,
    ]);

这是刀片文件。

<table class="table table-striped">
<thead>
    <tr><th class="text-center" colspan="5">Transactions</th></tr>
    <tr>
        <th class="text-center">TranId</th>
        <th class="text-center">Tran Date</th>
        <th class="text-center">SubType</th>
        <th class="text-center">Filed Date</th>
        <th class="text-center">Amount</th>
    </tr>
</thead>
<tbody>
@forelse ($transactions AS $transaction)
    <tr>
        <td class="text-center">{{ $transaction->TranId }}</td>
        <td class="text-center">{{ $transaction->TranDate }}</td>
        <td class="text-center">{{ $transaction->SubType }}</td>
        <td class="text-center">{{ $transaction->FiledDate }}</td>
        <td class="text-center">{{ number_format($transaction->Amount, 2, '.', ',') }}</td>
    </tr>
@empty
    <tr><td colspan="5">No Transactions</td></tr>
@endforelse
</tbody>              

我创建了一个虚拟事务数组,但仍然遇到同样的错误。

此外,当我使用该foreach指令时,它可以正常工作,但是我必须进行额外的测试以检查是否没有记录。

4

4 回答 4

1

失败的不是迭代的执行,而是 Blade 模板的编译。差异对于调试问题至关重要。直到9 月 18 日,指令的编译forelse都是区分大小写的,这意味着当它试图编译您的语句时,它无法生成输出所需的实际 PHP 代码所需的匹配项。更新 Laravel 应该可以解决这个问题。

因此,为了澄清,这将打破:

@forelse ($transactions AS $transaction)

虽然这会起作用:

@forelse ($transactions as $transaction)

话虽如此,我强烈建议您遵循PSR-2并将所有 PHP 关键字写成小写

于 2016-12-02T22:47:26.303 回答
0

您只需要更新您的@forelse 部分,如下所述:

@forelse ($transactions ? $transactions : [] as $transaction)
    <tr>
        <td class="text-center">{{ $transaction->TranId }}</td>
        <td class="text-center">{{ $transaction->TranDate }}</td>
        <td class="text-center">{{ $transaction->SubType }}</td>
        <td class="text-center">{{ $transaction->FiledDate }}</td>
        <td class="text-center">{{ number_format($transaction->Amount, 2, '.', ',') }}</td>
    </tr> @empty
    <tr><td colspan="5">No Transactions</td></tr> @endforelse
于 2018-02-06T01:09:21.967 回答
0

您是否尝试过转储交易的内容?它可能没有您在 forelse 循环中访问的字段,从而导致错误。

尝试在 forelse 循环中执行 {{var_dump($transaction)}} 并确保在代码中拥有所有要访问的字段。

于 2016-08-30T20:57:11.467 回答
0

在控制器中以这种方式创建 $transaction: $transacrion 不是数组:使用此代码:

$transaction = Transaction::all();
于 2016-08-31T07:47:19.097 回答