1

I'm using Laravel 4.2. I have a method for storing files and I'm trying to push items in session array. Every time user clicks on a button, I want to save these file names in session array with a name and later I should get them.

I'm trying with the following code:

$name = Input::get('name');
$input = Input::all();
foreach ($input[$name] as $key => $corporate) {

  $file_name = $key.'_'.$current_time . '_' . $corporate->getClientOriginalName();
  //code for uploading files
  if(Session::has($name)) {
     Session::push($name.".".$key, $file_name); //I want to add new items in this array
  } else {
    Session::put($name, $file_name); //for first image
  }


}

As I read from laravel docs:

Push A Value Onto An Array Session Value

Session::push('user.teams', 'developers');

);`

But it doesn't add new items to array, it overwrites it.

After first image upload in session array I have:

["director_front_passport[]"]=>
  array(1) {
    [1]=>
    array(1) {
      [0]=>
      string(54) "0_1472669237_12894473_678457885627912_1258115018_o.jpg"
    }
  }

After uploading second image, session is:

["director_front_passport[]"]=>
  array(1) {
    [2]=>
    array(1) {
      [0]=>
      string(33) "0_1472669255_animated_loading.gif"
    }
  }

What is the proper way to push items in session array with definite name, I mean I should get these items later using: Session::get('name') for example.

1 Answer 1

1

You can try the following code:

$name = Input::get('name');
$input = Input::all();
$items = Session::get($name, []);
foreach ($input[$name] as $key => $corporate) {
  $file_name = $key.'_'.$current_time . '_' . $corporate->getClientOriginalName();
  if (!array_key_exists($key, $items)) {
      $items[$key] = [];
  }
  $items[$key][] = $file_name;
}
Session::put($name, $items);
Sign up to request clarification or add additional context in comments.

3 Comments

I use this method when I should add new item to existing session array. That's why I need this check if I have a session - if(Session::has($name)) { Session::push($name.".".$key, $file_name); } else { Session::put($name, $file_name);
But if you're storing multiple items at the same Session key, it makes more sense to store an array of items. Having one item each at a number of similar addresses ('name', 'name0', 'name1', etc) isn't as clean as having Session::get('name') = [item0, item1, item2, ...]
My code will push the item if it doesn't exist after the loop. I cannot check on my local machine. But it would be helpful if you print the result and tell what is wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.