Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

peppeto's avatar

Help with pivot

Hi, I need some help with additional column in pivot table. I have three tables materials products material_product with fields material_id, product_id and is_cover is_cover is determining if the material is cover or not I have build relations

public function products() {
            return $this->belongsToMany( Product::class )->withTimestamps();
    }

public function materials() {
            return $this->belongsToMany( Material::class );
        }

When I save the form I have

    private function syncMaterials( $product, array $materials ) {
            $product->materials()->sync( $materials );
        }

        
    private function syncCoverMaterials( $product, array $materials ) {
            $product->coverMaterials()->attach( $materials, [ 'is_cover' => 1 ] );
        }

The problem is when I'm using form, I don't know how to display the selected cover materials in select box

 <div class="form-group">
        {{ Form::label('materials_list', trans('labels.general.materials'), ['class' => 'col-lg-2 control-label']) }}
        <div class="col-lg-10">
            {{ Form::select('materials_list[]',  $materials, null, ['class' => 'form-control select2', 'multiple','required' => 'required']) }}
        </div>
    </div>

<div class="form-group">
        {{ Form::label('cover_materials_list', trans('labels.general.cover_materials'), ['class' => 'col-lg-2 control-label']) }}
        <div class="col-lg-10">
            {{ Form::select('cover_materials_list[]',  $coverMaterials, null, ['class' => 'form-control select2', 'multiple']) }}
        </div>
    </div>
0 likes
4 replies
Tray2's avatar

First of all you shouldn't use the Laravel Collective HTML form it gives you headaches when it comes to debugging and readability.

This is how I would do it.

<select name="materials" required multiple id="material">
    @foreach ($materials as $material)
        <option value="{{$material->id}}">{{ $material->name }}</option>
    @endforeach
</select>
peppeto's avatar

@TRAY2 - You are right about Laravel Collective HTML but I still cannot solve my problem to make selected materials from pivot table with is_cover=1

Tray2's avatar

What does the controller method look like?

peppeto's avatar

@TRAY2 - I've got it I just have to send the chosen items from pivot table. Thank you very much for your time.

Please or to participate in this conversation.