How to save multiple checkboxes in the database with Laravel?

1

I'm developing a site in Laravel and wanted to know how to controller should be able to save multiple checkboxs chosen in the database.

form file:

<!DOCTYPE html> <html lang="pt-br"> <head>   <meta charset="utf-8">
        <title> Testando conexão ao banco de dados </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body>
         <div class="container">   <h3 class="panel-heading">Formulário de Cadastro de Clientes</h3><br>
        <hr>
         <div class="panel-body">   <form name="Cadastro" action="{{ route('enviarDados') }}" method="POST">    {{ csrf_field() }}

        <input type="text" name="nome" value="{{ isset($cadastro->nome) ? $cadastro->nome : '' }}" placeholder="Seu nome!"> <br><br>
        <input type="text" name="idade" value="{{ isset($cadastro->idade) ? $cadastro->idade : ''}}" placeholder="Sua
    idade!"> <br><br>

        <input type="checkbox" name="checkbox[]" value="Mysql"> Mysqlss <br>
        <input type="checkbox" name="checkbox[]" value="Java"> Java <br>
        <input type="checkbox" name="checkbox[]" value="Sqlite"> Sqlite <br>
        <input type="checkbox" name="checkbox[]" value="Laravel"> Laravel <br><br>
        <button class="btn btn-primary"> Salvar </button>   </form> <br><br>   </div> </div>
</body>

Controller to save:

public function salvar(Request $req) {

    $novocadastro = new Cadastro;
    $novocadastro->nome = $req->nome;
    $novocadastro->idade = $req->idade;
    $novocadastro->save();

    $categorias = $req->get('checkbox[]');
    foreach ($categorias as $novocheckbox) {

        $novocheckbox = new Checkbox;
        $novocheckbox->cadastro_id = $novocadastro->id;
        $novocheckbox->save();

    }

Checkbox Table

Schema::create('checkboxes', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('cliente_id')->unsigned();
        $table->foreign('cliente_id')->references('id')->on('clientes')->onDelete('cascade');
        $table->string('item');
        $table->timestamps();
    });
    
asked by anonymous 13.03.2017 / 19:32

2 answers

0

It's so :

$categorias = $req->get('checkbox[]');

Switch by :

$categorias = $req->get('checkbox');

And in its foreach , it has passed to categoria :

foreach ($categorias as $novocheckbox) 
{
    $novocheckbox = new Checkbox;
    $novocheckbox->cliente_id = $novocadastro->id;
    $novocheckbox->item = $novocheckbox; 
    $novocheckbox->save();
}

Example: Subbmiting form with array of text fields.

    
13.03.2017 / 20:31
0

I like to use saveMany ().

link

    
06.11.2018 / 03:04