Search code examples
laravelmany-to-many

Laravel Many to Many sync with null


I'm trying to use sync function like that:

$round->competitors()->sync($fighters);

$fighter is :

Collection {#339 ▼
  #items: array:3 [▼
    0 => 5
    1 => null
    2 => 6
  ]
}

When it get to the null element, I get :

QueryException in Connection.php line 647:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column 'competitor_id' at row 1 (SQL: insert into `round_competitor` (`competitor_id`, `round_id`) values (, 29))

I get the same result if I try:

$round->competitors()->sync([null, null]);

But if I try:

$round->competitors()->attach(null);

it works without any problem???

Why is that happening???


Solution

  • Call filter() on your $fighters so that the null values are removed.

    $round->competitors()->sync($fighters->filter());