CodeIgniter Forums

Full Version: Proper way to get array from session
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a session which contains an item called "error", this item contains an array with the following structure:

array(1) { ["meta.featured_image"]=> string(60) "Il file meta.featured_image supera le dimensioni consentite." }

I'm trying to print the item featured_image, so I did
this:

PHP Code:
<?= session('error.meta.featured_image'?>


But the code above returns NULL

but if I do 

PHP Code:
<?= session('error')['meta']['featured_image'?>

works but I need to check if the index exists to prevent error, there is no way to get the featured_image index directly in the session?
I do not believe that sessions work with the dot notation on session arrays.
PHP Code:
session('error.meta.featured_image'
//equal
session('error')['meta']['featured_image']
// and match
['error' => ['meta' => ['featured_image' => '...']]]

// and does not match 
['error' => ['meta.featured_image' => '...']] 
(04-17-2021, 09:26 PM)iRedds Wrote: [ -> ]
PHP Code:
session('error.meta.featured_image'
//equal
session('error')['meta']['featured_image']
// and match
['error' => ['meta' => ['featured_image' => '...']]]

// and does not match 
['error' => ['meta.featured_image' => '...']] 

I already tried with the first one and I get NULL how is that possible? ?
This will return null because there is no matching data.

You cannot get the data using:
session('error')['meta']['featured_image']
for ['error' => ['meta.featured_image' => '...']]
(04-18-2021, 03:20 AM)iRedds Wrote: [ -> ]This will return null because there is no matching data.

You cannot get the data using:
session('error')['meta']['featured_image']
for ['error' => ['meta.featured_image' => '...']]

the input I have is this:

PHP Code:
<input type="file" id="featuredImage" accept=".png, .jpg, .jpeg" name="meta[featured_image]"

I guess session('error.meta.featured_image') should be correct?
I will show you an example of how you can get out of this situation.
PHP Code:
// route 
$routes->add('/''Home::index');
// in controller 
public function index()
{
    if (
$this->request->getMethod() !== 'get') {
        if (! 
$this->validate(['a.c' => 'required'])) {
            return 
redirect()->to('/')->withInput();
        } else {
            
d('win');
        }

    } else {
        
session(); 
        return 
view('template', ['validator' => Services::validation()]);
    }
}
// template
<?php /** @var Codeigniter\Validation\Validation $validator */ ?>
<h1>error: <?= $validator->getError('a.c')?></h1>
<form method="post" action="/">
    <input type="text" name="a[b]" value="aa">
    <input type="submit">
</form> 

Anyway, I added a PR to access the key containing the dot using dot notation.
https://github.com/codeigniter4/CodeIgniter4/pull/4588