PHP Laravel返回查看空变量


PHP Laravel return to view null variable

>我有办法获取单词形式搜索栏并在数据库中查询,然后返回查看

但它显示空表,尽管我检查空变量

这是控制器代码

<?php
    public function getSearch($title) {
            $words = Word::where('title', $title)->first();
            if (empty($words)) {
                abort(404);
            }
            return view('dict.index', compact('words'));
        }

这是查看代码

<?php
    foreach ($words as $row) {
        echo '<tr>';
        echo '<td>' . $row['title'] . '</td>';
        echo '<td>' . $row['meaning'] . '</td>';
        echo '<td>';
        for ($i = 0; $i < $row['rate']; $i++) {
            echo '<img src="/images/pjdict/star.png" width="20" height="20">';
        }
        echo '</td>';
        echo '</tr>';
    }

代码中有几个错误。对于初学者来说,您的查询将始终返回一个元素,而我认为您希望查询的所有结果。应使用 get 函数get查询中的所有行。

对雄辩集合使用 empty 永远不会返回false因为您将始终收到雄辩的对象或集合。 若要检查集合是否有任何值,可以使用 isEmpty 函数。

结果应该是这样的:

<?php
    public function getSearch($title) {
            $words = Word::where('title', $title)->get();
            if ($words->isEmpty()) {
                abort(404);
            }
            return view('dict.index', compact('words'));
        }

对于视图:

因为您使用的是 Eloquent,所以不必使用数组键来选择值,而应使用对象属性。这样:

<?php
    foreach ($words as $row) {
        echo '<tr>';
        echo '<td>' . $row->title . '</td>';
        echo '<td>' . $row->meaning . '</td>';
        echo '<td>';
        for ($i = 0; $i < $row->rate; $i++) {
            echo '<img src="/images/pjdict/star.png" width="20" height="20">';
        }
        echo '</td>';
        echo '</tr>';
    }

为了补充 Jerodov 的答案,一种更优雅的方法来编写您的视图,即使用刀片语法。

@foreach($words as $word)
<tr>
    <td>{{ $word->title }}</td>
    <td>{{ $word->meaning }}</td>
    <td>
    @for($i=0; $i<$word->rate; $i++)
        <img src="/images/pjdict/star.png" width="20" height="20" />
    @endfor
    </td>
</tr>
@endforeach

请记住在视图中添加.blade后缀。例如,dict.index.blade.php

https://laravel.com/docs/5.2/blade