Get property from Pivot Table extra attribute

Posted 1 year ago by priverop

I have a many-to-many relationship between Part and Material models. It's working perfectly with a pivot table.

Now I just added another column to the pivot table 'provider_id', so when I do:

@foreach($parts as $key => $value)
 @foreach($value->materials as $mkey => $mvalue)
  {{ $mvalue->provider_id }}
 @endforeach
@endforeach

I get the provider ID, thats ok. But I want to get it's name instead. Something like $mvalue->provider->name. How can I do it?

Here are my pivot table migration:

Schema::create('material_part', function (Blueprint $table) {

    $table->integer('part_id')->unsigned();
    $table->foreign('part_id')->references('id')
        ->on('parts')->onDelete('cascade');

    $table->integer('material_id')->unsigned();
    $table->foreign('material_id')->references('id')
        ->on('materials')->onDelete('cascade');

    $table->integer('provider_id')->unsigned();
    $table->foreign('provider_id')->references('id')
        ->on('providers')->onDelete('cascade');

    $table->timestamps();
  });

Part Model:

class Part extends Model
{
  public function materiales(){
   return $this->belongsToMany('App\Material', 'material_part')->withPivot('part_id', 'provider_id');
  }
}

I also have the same relationship in Material model, but nothing in Provider model.

Thanks!

Please sign in or create an account to participate in this conversation.