Has many through update / with pivot laravel 5.5


I have several tables (all of them with softdeletes and timestamps : created_at , updated_at , deleted_at ) :

  • sectors
  • lang_sector
  • valuechains
  • lang_valuechain
  • segments
  • lang_segment
  • keyneeds
  • keyneed_lang

the tables are linked in this order :

  • sectors has many valuechains AND A valuechain belongs to one sector
  • valuechains has many segments AND A segment belongs to one valuechain
  • segments has many keyneeds AND A keyneed belong to one segment

Here is my model :

<?php 
    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;

    class Sector extends Model
    {
        use SoftDeletes;

        protected $table = "sectors";
        protected $fillable = ['admin_id'];
        protected $dates = [ 'created_at', 'updated_at', 'deleted_at' ];

        public function langs() {
            return $this->belongsToMany('App\Lang')
                ->withPivot('sectname', 'sectshortname', 'segname_slug',
                    'sectdescription', 'sectshortdescription'
                )
                ->withTimestamps();
        }
        public function admin()
        {
            return $this->belongsTo('App\Admin');
        }
        public function valuechains()
        {
            return $this->hasMany('App\Valuechain');
        }
        public function segments()
        {
            return $this->hasManyThrough('App\Segment', 'App\Valuechain');
        }
        public function keyneeds()
        {
            return $this->hasManyThrough('App\Keyneed', 'App\Segment', 'App\Valuechain');
        } 
    }

In my destroy controller :

public function destroy($id)
{
    $sector = Sector::findOrFail($id);

    // $sector->delete();
    $sector_ids = $sector->langs()->allRelatedIds();
    foreach ($sector_ids as $id){
        $sector->langs()->updateExistingPivot($id, ['lang_sector.deleted_at' => Carbon::now()]);
    }

    $sector->valuechains()->delete();
    $sector->segments()->delete();
    $sector->keyneeds()->delete();
    return redirect()->route('sectors.index')->with('success', 'Sector deleted');
}

My issue is that it doesn't update the following tables : segments and keyneeds and their pivot tables too ... And that i have an error message :

it adds : updated_at

I succesfully updated :

  • sectors table
  • valuechains table

My issue is to update

  • lang_valuechain pivot table ...
  • segments table by using : $sector->segments()
  • keyneeds table by using : $sector->keyneeds()

And their pivot table as well... I read the documentation but it doesn't help.


Sign in to participate in this thread!


We'd like to thank these amazing companies for supporting us