Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 582
Félix Maroy Avatar asked Oct 14 '25 22:10

Félix Maroy


2 Answers

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; ?>
like image 67
porquero Avatar answered Oct 17 '25 12:10

porquero


The context ($this) is an instance of the View class --> you don't have access to the Session instance directly

You can create new instance below

$session = \Config\Services::session();
like image 35
Jerson Avatar answered Oct 17 '25 12:10

Jerson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!