Creating a select component using Blade

Viewed 1152

I am using Laravel 7.x and wondering if there is some built-in Blade feature that I am not seeing in the documentation to ease the process of creating a select HTML tag.

Assuming my controller action looks like the following:

public function index()
{      
  return view('cars.index', ['cars' => \App\Cars::all()]);
}

With HTML, I'd manually render the select input with the following hypothetical example:

<label for="cars">Choose a car:</label>

<select name="cars" id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Assuming the cars table has a name and id column (id being a substitute for value and name being the actual text of the option), is there a 'Laravel' or 'Blade' way to render this component? I've seen prior versions of Laravel use some kind of Form template tag. What is the modern way of rendering this select input?

1 Answers

As you say, you can use Form.

I would return the model values as an associative array (id => name):

return view('cars.index', ['cars' => \App\Cars::all()->keyBy('id')->pluck('id', 'name')]);

And then generate a Drop-Down like this:

{{ Form::select('cars', $cars) }}

EDIT 1

As lagbox pointed out in the comments, you'll need to install the laravelcollective/html package.

Related