Laravel - Relationship ManyToMany extra columns

2

I have the following scenario in a database:

Tables:

User

  • id,
  • name
  • email

Company

  • id
  • name

UserCompany

  • userid
  • business_id
  • start_date
  • data_termino

In this scenario, I need to bring the information of the Empresas that the user is part of and start date and end in each of them, in Eloquent I made a ManyToMany relationship, where on the Usuario side, I have a empresas() method with belongsToMany('Empresa', 'UsuarioEmpresa') .

How would you bring these fields of the relationship?

    
asked by anonymous 16.08.2017 / 18:32

1 answer

2

You can use the withPivot method when declaring the relation and providing the additional fields, here's an example.

 public function empresas()
 {
      return $this->belongsToMany('\App\Empresa', 
                                 'UsuarioEmpresa', 
                                 'id_usuario', 
                                 'id_empresa')->withPivot('data_inicio', 'data_termino');
 }

To access the columns date_inicio and date_termino in a view you can use:

@foreach( $model->empresas as $empresa )
    {{$empresa->pivot->data_inicio}}
    {{$empresa->pivot->data_termino}}
@endforeach
    
16.08.2017 / 18:50