I ran into an issue earlier where I needed to add a default message to a drop down box created through Laravel’s Form builder. The difficulty was that the form select doesn’t allow for a default option. You have to manually add that. If you pre-populate your select with an Eloquent model, you will have to deal with using a Collection. So how can you add to put an item at the head of the list?
It’s actually pretty simple. What you need to do is create a new Collection with an array structured to match your collection that you want to expose to your select drop down. Then you use the merge method on the Collection to combine the two. Here is an example:
$items = collect([['id' => null, 'name' => 'Select Your Item']])->merge(MyModel::all());
Notice that I start the collection with the item that I want to be at the head of the array I intend to pass into select. Also, note that this item is in a double array since you’re essentially merging one array of key/values pairs with another coming from your lookup table.
There might be other ways to handle this. But this seemed pretty straight forward.
Leave a Reply
You must be logged in to post a comment.