ManfredP
ManfredP

Reputation: 1047

Add row manually to eloquent result in Laravel 4.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:

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

Thanks in advance

Upvotes: 2

Views: 673

Answers (2)

Eazy Sam
Eazy Sam

Reputation: 308

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).

Upvotes: 1

Mark Walet
Mark Walet

Reputation: 1186

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

Upvotes: 0

Related Questions