How to validate Laravel 5.4 radio button?

20,241

If gender is a required field then you should also pass required validation to gander property like below

'gander'=> 'required|in:male,female' 

If it is not a required field then make the male column nullable in your database table.

And there is also a problem in your table design instead of putting male value to male and female value to female make on column with name gender and type boolean then set 0 for male and 1 for female.

If you don't want to use boolean then use enum datatype for gender.enum is the best option in your case.

Share:
20,241
Masum
Author by

Masum

Updated on July 06, 2021

Comments

  • Masum
    Masum almost 3 years

    How can I validate my radio button in Laravel 5.4?

    <div class="radio">
        <label><input name="gander" type="radio" value="male">male </label>
        <label><input name="gander" type="radio" value="female">female</label>
    </div>
    

    Controller

    /* Validate this form. */
    $this->validate(request(), [
        'title' => 'required',
        'body' => 'required',
        'gander' => 'in:male,female'
    ]);
    
    $post = new Post;
    $post->title = $request['title'];
    $post->body = $request['body'];
    $post->status = $request['status'];
    $post->male = $request['male'];
    $post->female = $request['female'];
    $post->save();
    
    return redirect('blog');
    

    When I submit the form, I get the following error.

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'male' cannot be null (SQL: insert into posts (title, body, status, male, female, updated_at, created_at) values (sdf, sdfsfsd, 0, , , 2017-03-01 13:09:54, 2017-03-01 13:09:54))

    That means that both of radio buttons' data need for database field. and into my table have these fields: 'title', 'body', 'status', 'male', 'female' 'created_at' & 'updated_at'.

    My problem is how to validate the radio button and how to insert data with the radio button value?

  • Masum
    Masum about 7 years
    so whats my solution?
  • Shahid Ahmad
    Shahid Ahmad about 7 years
    there is a problem in your table design make one enum column with name gender with values "male" and "female" instead of putting seperate column for male and female
  • jakub wrona
    jakub wrona about 7 years
    The solution is to change your model and table schema and replace two columns "male" and "female" with just one called "gender". Enum would be perfect.
  • Kamlesh
    Kamlesh over 4 years
    Zoe, It works for me. Thanks for devoting my comment. Kindly share right solution, if you are right.
  • mlila_p
    mlila_p over 2 years
    how can I set type boolean as male to 0 and female to 1?