Skip to content
Advertisement

Undefined database variable

Blog.php code below:

    <?php namespace AppControllers;
    
    use AppModelsBlogModel;
    
    class Blog extends BaseController
    {
        public function index()
        {
            $model = new BlogModel();
    
            //echo "<pre>";
    
            //print_r($model);
    
            $dados = [
                'posts' => $model->get()->paginate(5),
                'pager' => $model->pager
            ];
            return view('posts/blog_index', $dados);
        }

blog_index.php code below:

    <?= $this->extend('layouts/main') ?>
    
    <?= $this->section('content') ?> 
 

    <?= $this->include('/components/busca_blog', $dados['posts'] ) ?>   
    <?= $this->include('/components/posts_recentes', $dados['posts'] ) ?>   
    <?= $this->include('/components/categorias', $categorias) ?>   
    <?= $this->include('/components/arquivo', $dados['posts'] ) ?>

I can’t see where is my mistake, it raises a errorException: “Undefined Variable:dados”. About $categorias variable, am learning how to use more than one table per controller.

Codeigniter version: 4.0.4 Running through xampp

Advertisement

Answer

Controller Blog.php

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

        $dados = [
            'posts' => $model->get()->paginate(5),
            'pager' => $model->pager
        ];
        return view('posts/blog_index', $dados);
    }
}

View blog_index.php

<?= $this->include('/components/posts_recentes', $posts) ?> 

    if(!empty($posts))
    {
        print_r($posts);
    }

Note :- For Reference see this:-

https://codeigniter4.github.io/userguide/outgoing/views.html#adding-dynamic-data-to-the-view

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement