Search code examples
phpcodeigniter

ErrorException Undefined array key in column table of CodeIgniter 4


I am having difficulty getting the blood type description to be displayed in my patients table due to receiving the blood type foreign key in Codeigniter 4.

The error happen in <td><?php echo $p['bt']['description']; ?></td> showing ErrorException Undefined array key "bt"

  • PacientModel.php
class PacientModel extends Model
{
    ...
    public function bt()
    {
        return $this->belongsTo(BloodTypeModel::class, 'blood_type_id');
    }
}
    
  • BloodTypeModel.php
class BloodTypeModel extends Model
{
    ...
    public function blood_type()
    {
        return $this->hasMany(PacientModel::class, 'blood_type_id');
    }
} 
  • PacientController.php
    public function index()
    {
        $model = new PacientModel();
        $blood_type = new BloodTypeModel();

        $blood_types = $blood_type->findAll();
        $blood_types = array_column($blood_types, null, 'id');

        $pacients = [
            'pacients' => $model->paginate(10),
            'pager' => $model->pager,
            'blood_types' => $blood_types, 
        ];
        return view('pacient/index', $pacients);
    }
  • index.php
  <?php foreach($pacients as $p): ?>
   <tr> 
     <td><?php echo $p['bt']['description']; ?> </td>
   </tr>
  <?php endforeach; ?>

Solution

  • The issue is CodeIgniter 4 does not support eager loading out of the box, you need to manually join the tables or map the relationships in your controller before passing the data to the view. PacientController.php >>

    public function index()
    {
        $model = new PacientModel();
        $pacients = $model->select('pacients.*, blood_types.description as bt_description')
                          ->join('blood_types', 'pacients.blood_type_id = blood_types.id', 'left')
                          ->paginate(10);
    
        $data = [
            'pacients' => $pacients,
            'pager' => $model->pager
        ];
    
        return view('pacient/index', $data);
    }
    

    index.php

    <?php foreach($pacients as $p): ?>
    <tr> 
      <td><?php echo $p['bt_description']; ?> </td>
    </tr>
    <?php endforeach; ?>