skip to Main Content

I’m brand new to CodeIgniter, so apologies if I’m missing something obvious here.

I’m comfortable with sending data from a controller to a view file using return view('default/blog/index', $data);. My issue is accessing the same data in a layout file which is extended by the view file using <?= $this->extend('layouts/default'); ?>.

For example, if I insert <?= $data['content'] ?> in my view file, it displays as expected. If I insert the same code in the layout file that is extended by my view file, I get the "Trying to access array offset on value of type null" exception.

What am I missing that will allow me to access my data from within the layout file?

Thanks in advance.

Update:

So in my BlogController I’ve got

class BlogController extends BaseController
{
    public function index()
    {
        $model = new Blog();

        $data = $model->getBlog();

        return view('default/blog/index', ['data' => $data]);

    }


    public function item($slug = null){

        $model = new Blog();

        $data = $model->getBlog($slug);

        return view('default/blog/item', ['data' => $data]);

    }

}

And then in my item.php and index.php files, I have

<?= $this->extend('layouts/default', ['data' => $data]); ?>

My Blog Model’s getBlog() method:

public function getBlog($slug = false)
{
    if ($slug === false) {
        return $this->orderBy('bs_created_dt', 'desc')->findAll();
    }

    return $this->where(['bs_slug' => $slug])->first();
}

When I use the debug toolbar to inspect the data, it is showing as expected, and I can display it in the view files, but not in the layout file.

2

Answers


  1. Chosen as BEST ANSWER

    Figured this out - absolute rookie mistake.

    I'm working off of a pre-existing template, and the previous developer had overwritten the $data variable in layout file before where I was trying to use it.

    I'm off to stand in the corner for a while.


  2. In Codeigniter, you need to pass data also in an extended file called layouts.

    Because you want to access data inside the extended file and for that, you just need to pass data to that file.

    So replace the line of code of extended view with this :

    $this->extend('layouts/default', ['data' => $data]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search