Storing Data in Session
Use the session()
helper function or the Config\Services::session()
method to access the session instance.
Storing Grouped Session Data
Use the session()->set()
method to store an array under a key.
1 2 3 4 5 6 7 | $sessionData = [ 'user_id' => $result[0]->id, 'user_name' => $result[0]->uname, 'email' => $result[0]->uemail, ]; session()->set('logged_in', $sessionData); |
Retrieving Grouped Session Data
To retrieve all data under the logged_in
key:
1 2 3 4 5 6 7 | $loggedInData = session()->get('logged_in'); if ($loggedInData) { echo "User ID: " . $loggedInData['user_id']; echo "User Name: " . $loggedInData['user_name']; echo "Email: " . $loggedInData['email']; } |
Updating Grouped Session Data
To update a specific value within the grouped session data:
1 2 3 4 5 6 7 | $loggedInData = session()->get('logged_in'); // Update the user's name $loggedInData['user_name'] = 'New Username'; // Save the updated data back to the session session()->set('logged_in', $loggedInData); |
Removing Grouped Session Data
To remove all data under the logged_in
key:
1 | session()->remove('logged_in'); |
Checking if Grouped Data Exists
To check if the logged_in
key exists in the session:
1 2 3 4 5 | if (session()->has('logged_in')) { echo "User is logged in"; } else { echo "User is not logged in"; } |
Storing Data Under Multiple Groups
If you need multiple grouped sessions, you can store different arrays under different keys:
1 2 3 | session()->set('logged_in', $userData); // User login data session()->set('cart', $cartData); // Cart data session()->set('preferences', $prefs); // User preferences |
To retrieve them individually:
1 2 3 | $userData = session()->get('logged_in'); $cartData = session()->get('cart'); $prefs = session()->get('preferences'); |