Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jason100's avatar

Session: Simple push but nested foreach to extract?

So I've got this code and the important part is the
"Session::push('offices', $offices);" , I just left the "echo" and "var_dump"s to show what's happening.

$offices = array();
foreach($locations2 as $l2){
    echo $l2->name;
    $offices[] = $l2->name;;
}
echo "<br/>";
var_dump($offices);
Session::push('offices', $offices);
echo "<pre>";
$data2 = Session::all();
var_dump($data2);
echo "</pre>";

And my output:

ParisBarcelona
array(2) { [0]=> string(9) "Paris" [1]=> string(13) "Barcelona" }

array(8) {
  ["_token"]=>
  string(40) "M1crVMEI0tc0mBzNUMhoXnr6TpDMVrea10KmUA2y"
  ["_previous"]=>
  array(1) {
    ["url"]=>
    string(63) "http://xx/xx/xx/xx/register"
  }
  ["flash"]=>
  array(2) {
    ["old"]=>
    array(0) {
    }
    ["new"]=>
    array(0) {
    }
  }
  ["usrid"]=>
  int(206)
  ["userFname"]=>
  string(2) "Aa"
  ["userLname"]=>
  string(2) "Bb"
  ["userRole"]=>
  string(19) "XXXXX"
  ["offices"]=>
  array(1) {
    [0]=>
    array(2) {
      [0]=>
      string(9) "Paris"
      [1]=>
      string(13) "Barcelona"
    }
  }
}

Seems like a pretty straight-forward '::push' into the Session var?
So, why do I have to use a nested foreach in my blade template to extract the values (Paris, Barcelona) like this?

@foreach(Session::get('offices') as $office)
    @foreach($office as $off)
        {{$off}},
    @endforeach
@endforeach

Is there a better way to insert these names into the Session such that I only need a single(non-nested) foreach to extract them?

0 likes
2 replies
usman's avatar
usman
Best Answer
Level 27

@derick100 Session::push is for pushing values into nested arrays. So when an array is not present it uses index 0 for the base and creates a nested array. Your problem will be solved if you use Session::put instead.

Snapey's avatar

I think push is expecting to merge into an existing array.

try this instead?

$offices = array();
foreach($locations2 as $l2){
    Session::push('offices', $l2->name);
}

Please or to participate in this conversation.