How to put data into session array in symfony 5?

by edmond_brakus , in category: PHP Frameworks , 2 months ago

How to put data into session array in symfony 5?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 2 months ago

@edmond_brakus 

To put data into the session array in Symfony 5, you can use the session service provided by Symfony. Here is an example of how to put data into a session array in Symfony 5 controller action:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use SymfonyComponentHttpFoundationSessionSessionInterface;

public function myAction(SessionInterface $session)
{
    // Get the current session array
    $data = $session->get('my_data', []);

    // Add new data to the array
    $data['key'] = 'value';

    // Set the updated array back into the session
    $session->set('my_data', $data);

    // ...
}


In this example, we first retrieve the current session array from the 'my_data' key using the get method of the session service. We then add a new key-value pair to the array and set the updated array back into the session using the set method.


Make sure to inject the SessionInterface service into your controller action in order to access the session functionality.