jlrdw's avatar
Level 75

Session array basic usage

Some folks new to Laravel have questions about session array's. This is just a basic example of usage. And I like the facade better, so add the use statement:

use Illuminate\Support\Facades\Session;

Suppose you wanted to store a companies name and phone, you would:

        Session::push('company.name', 'Acme Widgets');
        Session::push('company.phone', '915-999-9999');

And somewhere in the app you needed the phone:

    echo Session::get('company.phone.0');
   // use blade or php as desired

Again just a very basic example.

0 likes
3 replies
Snapey's avatar

The other thing that catches people out is that session changes are only saved if you explicitly call save() or the request cycle completes so that the terminable middleware runs. If the execution hits dd() or crashes then the session will not be changed.

1 like
jlrdw's avatar
Level 75

Plus what Snapey said, sometimes you need to loop over the array, This is how I do it:

$myarray = Session::get('company');
        $keys = array_keys($myarray);
        for ($i = 0; $i < 2; $i++) {
            foreach ($myarray[$keys[$i]] as $key => $value) {
                echo $keys[$i] . " : " . $value . "<br>";
            }
        }

Which produces:

name : Acme Widgets
phone : 915-999-9999

Of course you can use ul li, tr td, etc. Or however you display things.

I seldom need session array, but at times there are questions on it.

jlrdw's avatar
Level 75

Another technique is to build an array first:

$company = array(
            "name" => 'Acme Widgets',
            "phone" => '915-999-9999'
        );

Put array in session:

Session::put('company', $company);

Which makes the loop easier:

foreach (Session::get('company') as $key => $value) {
            echo $key . " : " . $value . "<br>";
        }

Which also produces:

name : Acme Widgets
phone : 915-999-9999

Please or to participate in this conversation.