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

davidvera's avatar

CRUD with Pivot Table

Hello,

I have 3 tables :

  • langs (id, name)
  • sectors (id)
  • lang_sector (name, description, created_at, updated_at, deleted_at)

For each Model (langs and sector) i created the link... Here is the function included in sector

public function langs(){
    return $this->belongsToMany('App\Lang')
        ->withPivot('sectname', 'sectshortname', 'sectdescription',  'sectshortdescription',
            'created_at', 'updated_at', 'deleted_at'
        );
}

In the index view I should display EACH sectors with : -> sectors.id -> lang_sector.name, -> lang_sector.description, -> lang_sector.created_at, -> lang_sector.updated_at, -> lang_sector.deleted_at

I want to display all sectors i create. So i created a SectorController with an index method :

public function index() {
    // Here I count the number of langs I created ... 
    $count = Lang::count();
    for ($id = 0; $id < $count; $id++) {
        // I made an echo of $langs[i]->name and i display the langs correctly
        $langs[$i] = Lang::find($i);
        }

    // Here is my problem ... if i wanted one entry i should write something like this : 
    $sectors = $langs->sectors()->get();
}

Thanks for your help

0 likes
1 reply
burlresearch's avatar

I think you need to specifically use the model key names on the pivot table, not your made-up names, for Laravel to pick these up, so:

->withPivot('name', 'description', 'deleted_at') // not even sure about soft-deletes on pivot
->withTimestamps();

With this change I think you will find accessing your pivot data works, like:

    $slDesc = $sector->pivot->description;

Please or to participate in this conversation.