Welcome Guest, Not a member yet? Register   Sign In
$session is not accessible to view
#1
Information 
(This post was last modified: 06-28-2020, 12:03 AM by jreklund.)

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.
Reply
#2

Hi, you need to assign it to the view.

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

echo 
view('BlogView'$data); 
Reply
#3

(This post was last modified: 06-28-2020, 01:04 AM by @nuj_3313.)

(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?
Reply
#4

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
Reply
#5

(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> 
Reply
#6

You can try to use the session helper method.

PHP Code:
<?= session('item');?>
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB