how to validate laravel 5.4 radio button?

2019-07-17 06:32发布

问题:

this is my radio button code

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

and my controller code is

   //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();

    //And then redirect to the home
    return redirect('blog');
}

when i submit this form it show this 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 both of radio button data need for database field. and into my table have these field 'title', 'body', 'status', 'male', 'female' 'created_at' & 'updated_at'

my problem is how to validate radio button & how to insert data with radio button value? Thanks.

回答1:

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

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

if it is not a require field then make the male column nullables in your database table.

and there is also 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 bollean then set 0 for male and 1 for female.

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



回答2:

The error message has nothing to do with the validation. The validation is passed and you do it properly. But your model seems weird, because instead of same "gender" column you have the male and female ones.



回答3:

Try to set the right names in your html:

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

Right now it looks for a gander column .

Of course you would have to edit your validation afterwards.



回答4:

Radio required featured works with laravel:

@foreach($status_list as $status_key => $status)

  {!! Form::radio('status', $status_key, false, array('id'=>'status_'.$status_key, 'required'=>'required' )); !!}

  {!! Form::label('status_'.$status_key, $status ) !!}

@endforeach