I am starting to learn Yii framework so I am a beginner. I am struggling. I want to fetch the data from database using yii2 framework. This is my controller
public function actionView()
{
$this->view->title = 'List Hotels';
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
return $this->render('index', [
'items' => $items,
]);
}
In my view file, I used the fetched data as below;
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'Hotel list';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php foreach ($items as $item): ?>
<p> <?= $item-> name ?></p>
<p> <?= $item->address ?></p>
<p> <?= $item->description ?></p>
<?php endforeach; ?>
When I wrote var_dumps($items) under $items I can see the datas. However in the view It says Trying to get property 'name' of non-object. What did I wrong here please guide me. THanks for your time.
ArrayHelper::map()
Returns an array where, in your case, second argument passed is a key, the third is a value. So you need to access its elements as an array elements instead of class properties. Like:
<?php foreach ($items as $key => $value): ?>
<p> <?= $key ?></p>
<p> <?= $value ?></p>
<?php endforeach; ?>
More details here: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basearrayhelper#map()-detail
But if you need to access data as class properties change the line in your controller:
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
to:
$items = Hotel::find()->all();