Non Brazilian Non Brazilian - 7 months ago 22
PHP Question

PHP Laravel return to view null variable

i have method to get word form searchbar and query in db,then return to view

but it show empty table although i check for null variable

this is controller code

<?php

public function getSearch($title) {
$words = Word::where('title', $title)->first();
if (empty($words)) {

abort(404);
}
return view('dict.index', compact('words'));

}


here is view code

<?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>';
}

Answer

There are several mistakes in your code. For starters your query will always return one element, while I supose you want all results from the query. You should use the get function to get all rows from the query.

Using empty on an eloquent collection will never return false because you will always receive an eloquent object or a collection. to check if your collection has any values, you can use the isEmpty function.

The result should be something like this:

<?php

    public function getSearch($title) {
            $words = Word::where('title', $title)->get();
            if ($words->isEmpty()) {
                abort(404);
            }

            return view('dict.index', compact('words'));
        }

For the view:

Because you are using eloquent, you don't have to use array keys to select the values, you should use object properties. Like so:

<?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>';
    }