Laravel Much to Many?

2

I have this model

public function exercicio()
{
    return $this->belongsToMany(Exercicio::class);
}

and

public function treino()
{
    return $this->belongsToMany(Treino::class);
}

My Controller

public function salvarTreino(Request $request)
{

}

How do I save a workout list?

It's currently like this

public function salvarTreino(Request $request)
{
    $treino = new Treino();
    $treino->nome = $request->nome;
    $treino->save();
    $treino->exercicio()->attach([1]);
    return response()->json("", 201);


}

however I am manually passing the exercise id, I want the user to be able to choose

    
asked by anonymous 15.10.2016 / 00:30

1 answer

2

You should use checkbox.

So you could build your form in a similar way:

<form method="POST">
      @foreach($exercicios as $exercicio)
          <label>
               <input type="checkbox" name="exercicios[]" value="{{ $exercicio->id }}" />
          </label>
      @endforeach
</form>

After submitting the submit, you can capture the data in the controller like this:

public function salvarTreino(Request $request)
{
    // Valida para saber se os dados estão corretos
    $this->validate($request, [
        'exercicios' => 'required|array'
    ]);

    $treino = new Treino();

    $treino->nome = $request->nome;

    $treino->save();

    // Pega os exercícios selecionados e adiciona-o ao Treino
    $treino->exercicio()->attach($request->exercicios);

    return response()->json("", 201);


}

If you do not want to use checkbox , you could also use select with multiple option.

    
25.10.2016 / 12:50