Search code examples
laravelinsertmany-to-manypivot-table

How to insert multiple values on a pivot table?


I'm trying to insert multiple values in a pivot table.

The tables are Participantes and Eventos (Participants and Events).

My idea is create a list that prints the values that aren't in the pivot list, then select all values that I want to insert with checkbox. Then pass all the values to the Controller and insert that.

Here is my Evento model:

class Evento extends Model
{
    protected $primaryKey = 'id_evento';
    public function participantes(){
        return $this->belongsToMany('App\Participante', 'evento_participante', 'id_evento', 'id_participante' );  
    }
}

Here is my Participante model:

class Participante extends Model
{
    protected $primaryKey = 'id_participante';

    public function eventos(){
        return $this->belongsToMany('App\Evento', 'evento_participante', 'id_participante', 'id_evento');
    }

Here is the modal where is the list. It's on(Evento) show.blade template:


<div class="modal fade bd-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content modal-lg">
      <div class="modal-header " >
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Nuevo Evento</h4>
      </div>

      <form action="{{ route('evento.update', ['evento' => $evento->id_evento]) }}" method="POST">
           @csrf
        <input type="hidden" name="_method" value="PUT"/>

             <table id="table_id2" class="table table-hover table-bordered display">
        <thead>
            <!--<th style="width: 10px;"><button type="button" class="btn btn-default btn-sm checkbox-toggle"><i class="fa fa-square-o"></i></button></th>-->


                <th>Nombre</th>
                <th>Apellidos</th>
                <th>Sexo</th>
                <th>Categoría</th>
                <th>Edad</th>
                <th>Club</th>
                <th>Cinturón</th>
                <th></th>

        </thead>

            <tbody>
            @foreach ($participantes as $participante)
                        @if (Auth::user()->hasRole('Administrador'))

        <tr>


        <td >{{$participante->nombre}}</td>
        <td>{{$participante->apellidos}}</td>
        <td>{{$participante->sexo}}</td>
        <td>{{$participante->categoria->nombre}}</td>
        <td>{{\Carbon\Carbon::parse($participante->fecha_nacimiento)->age}}</td>
        <td>{{$participante->club->nombre}}</td>
        <td>{{$participante->cinturon}}</td>
        <td><input type="checkbox" name="insertar"/></td>
        </tr>

        @endif
        @endforeach
        <tfoot>
            <tr>

                <th>Nombre</th>
                <th>Apellidos</th>
                <th>Sexo</th>
                <th>Categoría</th>
                <th>Edad</th>
                <th>Club</th>
                <th>Cinturón</th>
            </tr>
        </tfoot>
            </tbody>
      </table>




      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Guardar</button>
      </div>
      </form>
    </div>
  </div>
</div>

And Here is my EventoController:

    public function show($id_evento)
    {

        $evento = Evento::find($id_evento);
        //$participantes = Participante::all();
        $participantes = Participante::get();


        return view('evento.show', ['evento' => $evento], ['participantes' => $participantes]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Evento  $evento
     * @return \Illuminate\Http\Response
     */
    public function edit(Evento $evento)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Evento  $evento
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Evento $evento)
    {
        $evento->update($request->all());
        //$evento=save();
        if($request->has('test')){
        $evento->participantes()->sync([$request->input('id_participante')]);


        }

That's returns a white screen. The URL is /evento/{id} (1 in this case).

Thanks, sorry for my english.


Solution

  • You can use sync() method to store multiple records into pivot table, this method accept an array with values.

    Using you model as example, you can do this:

    $evento->participantes()->sync([1,2,3,4]);
    

    This will attach participantes to your evento;

    Here you can find more about https://laravel.com/docs/5.8/eloquent-relationships#updating-many-to-many-relationships