CodeIgniter Forums
$session is not accessible to view - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=31)
+--- Thread: $session is not accessible to view (/showthread.php?tid=76864)



$session is not accessible to view - @nuj_3313 - 06-27-2020

Hi all,
I am new to CI4 I am trying to access the session in view but I am getting an error saying  Undefined property: CodeIgniter\View\View::$session,

I have created one default controller by extending BaseController and have initialized the session as below
$this->session = \Config\Services :: session();

so the $this->session is accessible to the controller but not on the view. however, the $_SESSION is working fine on the view.
and the same case with flashdata it is working in controllers but not on the view
Please help me!... 
Thank you.


RE: $session is not accessible to view - jreklund - 06-28-2020

Hi, you need to assign it to the view.

PHP Code:
$data = [
    
'session' => $this->session,
];

echo 
view('BlogView'$data); 



RE: $session is not accessible to view - @nuj_3313 - 06-28-2020

(06-28-2020, 12:04 AM)jreklund Wrote: Hi, you need to assign it to the view.

PHP Code:
$data = [
    'session' => $this->session,
];

echo 
view('BlogView'$data); 
Thanks! it's work!
But is it really required to assign it to view, is it not available automatically, I mean I also have to use the URI segment and other things also so everything needs to pass to the view?


RE: $session is not accessible to view - jreklund - 06-28-2020

Yes, you are required to pass everything you want to be echoed out to the view.

We follow the MVC pattern and the view knows nothing on what's going on in your Controller.
https://codeigniter.com/user_guide/concepts/mvc.html


RE: $session is not accessible to view - dave friend - 06-28-2020

(06-28-2020, 12:56 AM)@nuj_3313 Wrote: Thanks! it's work!
But is it really required to assign it to view, is it not available automatically, I mean I also have to use the URI segment and other things also so everything needs to pass to the view?

It is necessary to pass any needed data to the view explicitly. The reason is that the "view" is in a different scope than the controller.

However, keep in mind that the Session class is a wrapper around the Superglobal $_SESSION. You can access that easily from a view. For instance, assuming a person's name is saved in the session you should be able to do this in a view.

PHP Code:
<div><?= $_SESSION['name']; ?></div> 



RE: $session is not accessible to view - InsiteFX - 06-29-2020

You can try to use the session helper method.

PHP Code:
<?= session('item');?>