Search code examples
phpcodeignitercodeigniter-4

CodeIgniter 4 - How to display Flashdata inside a View?


I'm upgrading my project from CodeIgniter 3 to CodeIgniter 4, I'm trying to display a flashdata message inside a view but unfortunately I get differents error for each method I try.

In CodeIgniter 3, I used to call something like:

<?php if ($this->session->flashdata('message')) : ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo $this->session->flashdata('message'); ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
<?php endif; ?>

I try the same in CodeIgniter 4 but I get this error:

ErrorException
Undefined property: CodeIgniter\View\View::$session

Can any one show me how to achieve this ? Thanks in advance.


Solution

  • You can use session() function directly:

    <?php if (session()->getFlashdata('message') !== NULL) : ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo session()->getFlashdata('message'); ?>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        </div>
    <?php endif; ?>