Creating a Radio Button Input Field

Problem

You want to create a radio button field for your Blade template.

Solution

Use the Form::radio() method.

You're only required to use the first argument, name.

{{ Form::radio('single') }}

This produces the following HTML.

<input name="single" type="radio" value="single">

But, radio buttons make the most sense when you have several with the same name, but different values. Specify the value with the second argument.

{{ Form::radio('sex', 'male') }}<br>
{{ Form::radio('sex', 'female') }}

Now the value will either be 'male' or 'female'.

<input name="sex" type="radio" value="male"><br>
<input name="sex" type="radio" value="female">

If you want to default the value as checked, pass true as the third argument.

{{ Form::radio('sex', 'male') }}<br>
{{ Form::radio('sex', 'female', true) }}

This adds the checked attribute to second radio button.

<input name="sex" type="radio" value="male"><br>
<input checked="checked" name="sex" type="radio" value="female">

Finally, you can add additional attributes to the input field with the fourth argument.

{{ Form::radio('example', 1, true, ['class' => 'field']) }}

Now the field has the class attribute.

<input class="field" checked="checked" name="example" type="radio" value="1">

Discussion

The appropriate radio button will automatically get checked based on any flash data.

If you redisplay the form because of errors, your radio button fields will retain what the user had previously.

Also, if you've bound a model to the form, it will pull the value from the model's data. See Creating a New Model Based Form.

comments powered by Disqus