How do I store 0 or 1 of a checkbox?

Asked

Viewed 342 times

0

How do I store 0 or 1 of a checkbox with Laravel?

Html

<div class="custom-control custom-checkbox">
  <input type="checkbox" name="dashboard" value="1" class="custom-control-input" id="Dashboard">
  <label class="custom-control-label" for="Dashboard">Dashboard</label>
</div>
<div class="custom-control custom-checkbox">
  <input type="checkbox" name="cadastro_pessoas" class="custom-control-input" id="Cadastro">
  <label class="custom-control-label" for="Cadastro">Cadastro de Pessoas</label>
</div>  

Controller Method

public function store(Request $request)
    {   
        $usu = new Usuario();
        $usu->usr_login = $request->input('login');
        $usu->usr_senha = $request->input('senha');
        $usu->usr_nome = $request->input('nome');
        $usu->usr_email = $request->input('email');
        $usu->usr_acesso_dashboard = $request->input('dashboard');
        $usu->usr_acesso_cadastro_pessoas = $request->input('cadastro_pessoas');
        $usu->usr_acesso_cadasto_gerais = $request->input('gerais');
        $usu->usr_acesso_relatorios = $request->input('relatorio');
        $usu->usr_acesso_prontuario = $request->input('prontuario');
        $usu->usr_acesso_configuracoes = $request->input('configuracoes');
        $usu->usr_acesso_consultas = $request->input('consulta');
        $usu->usr_ativo = $request->input('ativo');
        $usu->usr_perfil = $request->input('perfil');
        $usu->usr_acesso_cadusuarios = $request->input('cadusuarios');
        $usu->save();
        return redirect('/usuario');
    }
  • 1

    The answer worked, and I’m watching your user and you don’t interact with the crowd, because?

2 answers

0

When I work with checkbox always leave a default in the migrate:

$table->tinyInteger('dashboard')->default(0);

If the checkbox was not selected the request does not receive anything and to avoid making other validations also use isset, because when the checkbox has value sends value , but if it has no send 'on' make the sequel:

$usu->usr_acesso_dashboard = isset($request->dashboard)? 1 : 0;

0

The input checkbox when it is not selected does not pass value and how to resolve it in Laravel?

In the method $request->input pass the second parameter which is the default value, example:

$request->input('dashbord', 0);

That is, if chosen you will pass the value of it that is 1 if not the default value that is 0.

References

  • solved man!! but I had to use jquary because it was passing the value ON $('input[type="checkbox"]'). change(Function(){ this.value = this.checked ? 1 : 0; }); and had to set a value to 0 for inputs.

  • What you said about changing the value is not necessary! @Kleitonconceição

Browser other questions tagged

You are not signed in. Login or sign up in order to post.