Home > OS >  Undefined variable $home in Codeigniter 4
Undefined variable $home in Codeigniter 4

Time:11-05

I’m new to using CodeIgniter 4 and I’m encountering an issue. I’m getting an error message ErrorException: Undefined variable $home when trying to pass data from my controller to my view.

Here’s the code I’m using:

Model (App\Models\indexModel):

namespace App\Models;

use CodeIgniter\Model;

class indexModel extends Model
{
    protected $table = "home";

    protected $allowedFields = [
        'front_name',
        'back_name',
        'jalan',
        'email',
        'telepon',
        'facebook',
        'whatsapp',
        'instagram'
    ];
}

Controller (App\Controllers\Index):

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\indexModel;

class Index extends Controller
{
    public function indexController()
    {
        //model initialize
        $account = new indexModel();

        $data = array(
            'home' => $account->findAll()
        );

        echo view('partial/header', $data);
    }
}

View (partial/header):

<div >
    <div >
        <?php foreach ($home as $key => $account): ?>
            <a  href="<?= $account['facebook'] ?>">
                <i ></i>
            </a>
            <a  href="<?= $account['whatsapp'] ?>">
                <i ></i>
            </a>
            <a  href="<?= $account['instagram'] ?>">
                <i ></i>
            </a>
        <?php endforeach; ?>
    </div>
</div>

I’ve checked and it seems like my code is correct, but I’m still getting this error. Can anyone help me understand what’s wrong and how to fix it? Thank you!

CodePudding user response:

Instead of:

'home' => $account->findAll()

Use:

'home' => $account->findAll() ?? []
  • Related