Laravel Array Keys not Preserved

Currently running Laravel 4.1.31. In the controller an array is built of users with their id as the key:

$owners = User::get()->lists('username','id');

Printing the owners array out at the controller level would produce the following:
print_r($owners)

// Array
// (
//    [1] => user1
//    [2] => user2
//    [4] => user3  <--- key jumps to 4, this is correct
//    [5] => user4
//    [6] => user5
// )

However once the array is passed to a view the keys are not preserved, printing it out at the view level produces the following:
// Array
// (
//    [1] => user1
//    [2] => user2
//    [3] => user3  <--- key was replaced with 3, this is incorrect
//    [4] => user4       all values from this point on are now shifted
//    [5] => user5
// )

There was no 3 key in the original array however once it was passed to the view everything shifted to fill in the gap. This ends up causing problems as all id’s above 2 are now mismatched. How can the arrays keys be preserved?

Full controller method:

public function edit($id) {

  // get the task
  $task = $this->task->find($id);

  // grab all users for owner field
  $owners = User::get()->lists('username','id');

  // grab all projects for project field
  $projects = Project::get()->lists('title','id');

  // add placeholder to beginning of arrays
  array_unshift($owners, 'Select Owner');
  array_unshift($projects, 'Select Project');

  // return show view
  return View::make('tasks.edit', array(
    'task'     => $task,
    'status'   => $this->status,
    'projects' => $projects,
    'owners'   => $owners
  )); 

}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

array_unshift changes the keys of your array. It will reset them to sequence of numbers 0,1,2,3,…

Use this to add a value with key "" at the beginning of your array:

$owners = ['' => 'Select Owner'] + $owners;

Method 2

As noted in the comments, get rid of array_unshift on the two arrays. In the view, handle that as follows:

<select name="projects">
  <option value="">Select Project</option>
  @foreach($projects AS $project)
  <option value="{{ $project->id }}">{{ $project->title }}</option>
  @endforeach
</select>

Instead of making the first element a generic value, hardcode it before processing the @foreach to make a select.

Hope that helps!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x