2

I am using Laravel 4.2 and i fetch all locations with this code:

$locations = Location::all();

This Locations are displayed in a select box afterwards. How can i add an additional row to the results in order to show an empty first option in the select box.

The options then should be:

  • choose a location
  • location 1
  • location 2
  • ...

I just want to add an additional item to the result in $locations.

Thanks in advance

ManfredP
  • 1,037
  • 1
  • 12
  • 27
  • Possible duplicate of [How do I make a placeholder for a 'select' box?](https://stackoverflow.com/questions/5805059/how-do-i-make-a-placeholder-for-a-select-box) – Loek Apr 13 '18 at 08:56
  • No i want to know how to alter the eloquent result. I know how to do this in pure HTML – ManfredP Apr 13 '18 at 08:59

2 Answers2

1

You can use:

{!! Form::select('location', ['' => 'Select your location'] + $locations, null , ['class' => 'form-control']) !!}

to update the view. In Laravel 5 there are attribute accessors to append an extra field with your eloquent collection.

Few other ways to do this are:

  • $locations[null] = 'choose a location'; Form::select('location', $locations);

  • Form::select('location',[null=>'Please Select'] + $locations);

Another way is to loop through the result and update it. Use json_decode() or 'toArray()` to convert your result into array format.

Otherwise you have to store choose a location as the first row value in your locations table(I know that is inappropriate for the requirement).

Eazy Sam
  • 288
  • 1
  • 2
  • 9
0

You should look at the put method for collections:

https://laravel.com/docs/5.6/collections#method-put

This method is not available in 4.2. You should make a custom Collection class and use it in your model by overwriting the newCollection method. https://laravel.com/docs/4.2/eloquent#collections

Mark Walet
  • 1,147
  • 10
  • 21