laravel 9 sync pivot table incorrectly

485 Views Asked by At

when I want update pivot table by sync method, it sync data incorrectly in table.

pivot table before update

posted data

pivot table after update

 public function update(Request $request, Invoices $invoice)
    {
            $validated = $request->validate([
            'reference' => ['required', 'integer'],
            'title' => ['required', 'string'],
            'subtitle' => ['string', 'nullable'],
            'client_id' => ['required', 'integer'],
            'subtotal' => ['required', 'numeric'],
            'global_discount' => ['required', 'numeric'],
            'discount_type' => ['required', 'integer'],
            'total_discount' => ['required', 'numeric'],
            'total' => ['required', 'numeric'],
            'total_due' => ['required', 'numeric'],
            'note' => ['string', 'nullable'],
        ]);
        $invoice->update($validated);
        $invoice->items()->sync($request->get('invoice_item'));

        return redirect(route('invoice.index'));
    }

invoices model

class Invoices extends Model
{
    use HasFactory;
    use SoftDeletes;
    protected $primaryKey = 'id';

    protected $guarded = [];

    public function items()
    {
        return $this->belongsToMany(Items::class,'invoice_item')->withPivot('quantity','unit_price','total');
    }

}

items model:

class Items extends Model
{
    use HasFactory;
    use SoftDeletes;

protected $guarded = [];
  
    public function invoices()
    {
        return $this->belongsTo(Invoices::class,'invoice_item');
    }
}

first item_id in invoice_item is 1 But in the pivot table 2 is stored.

I hope you understand what I mean thanks

1

There are 1 best solutions below

1
On
 // This is course Model

class Course extends Model { 
    public function course_group() 
    { 
        return $this->belongsToMany(Course_group::class,'courses_course_groups','course_id','course_group_id'); 
    } 
}

// This is course group Model
class Course_group extends Model { 
    public function course() {
        return $this->belongsToMany(Course::class,'courses_course_groups','course_group_id','course_id'); 
    }
}

// In Controller
if($request->course_group_ids != 'null') {
     $country_groups = $request->course_group_ids; 
     $course_id = $course->id; 
     $course->course_group()->attach($country_groups); 
}