Too Loud for Too Many?

Asked

Viewed 259 times

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 an exercise list in training?

at the moment it’s 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 can choose

  • Your question is easy to answer but, I need to see the layout of the tables, the model in its entirety and your view to give a reliable and faithful answer to what you have! Just remembering that here is Stackoverflow in Portuguese!

  • I didn’t see it when I posted :/ so I won’t have the view, this controller will return a json.

  • Have a copy of Json and in it comes the code of training?

  • In save function I want the user to name the training and choose an exercise q has been previously registered

  • I understand, are you sending this data in what way? or is that your doubt?

1 answer

3

You should use checkbox.

So, you could assemble your form in a similar way to this:

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

After sending Submit, you can capture the data in the controller in this way:

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 don’t want to use the checkbox, you could also use a select with the option multiple.

Browser other questions tagged

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