5

I have a select box on a form which uses data that is listed from an Eloquent model (Laravel 4):

$campuses = Campus::lists('name', 'id');

And the form:

{{ Form::select('campus_id', $campuses) }}

However, I would like to have the first option on the form be Select... so that when the user has not selected an option yet, the first option does not become the default.

How can I prepend another option to the beginning of the Eloquent collection?

I've tried something like:

$campuses = array('Select...') . Campus::lists('name', 'id');
Dwight
  • 12,120
  • 6
  • 51
  • 64

2 Answers2

9

You could also do

$campuses = array('' => 'Select...') + Campus::lists('name', 'id');

This is the way I use it, sum 2 arrays

Israel Ortuño
  • 1,084
  • 2
  • 14
  • 33
3

You can merge 2 arrays with array_merge function.

So, the answer will be

$campuses = array_merge(array('Select...'), Campus::lists('name', 'id'));

Umut Sirin
  • 2,462
  • 1
  • 21
  • 31
  • in later version, we need to add ->all() after the ::list() argument. Because lists no longer return array, and adding ->all() will return them in array so we can use array_merge. – Agung Kessawa Dec 29 '16 at 02:52