Laravel how to set a checkbox value to checked based on models value

In this post I’ll show how to set a Laravel checkbox value to checked based on the value stored on the model.

In this example I’ll be using the Laravel Collective Form checkbox

{{ Form::checkbox('collected' /* name */, "yes" /*value*/, old('collected',  $gas_cert->collected=="yes"?true:false   ) /* true sets checked */ ) }}

In the code example above my checkbox is called ‘collected’ the value when checked is ‘yes’ , I wanted to populate my form with the value from the database stored on the model (which is yes or no on the $gas_cert->collected field of the model), the Form::checkbox wants a boolean to decide whether to check the checkbox or not.

I want the form to take either the last input to the collected input or the value in the database (ie if yes check the checkbox).

If I did want to just take into account the model value it could be simplified to this:

{{ Form::checkbox('collected' , "yes" , $gas_cert->collected=="yes"?true:false  ) }}

 

 

 

Leave a Comment