Juliatzin
Juliatzin

Reputation: 19695

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???

Upvotes: 0

Views: 1536

Answers (2)

Dwight
Dwight

Reputation: 12450

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

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

Upvotes: 2

ettdro
ettdro

Reputation: 350

If you do: $round->competitors()->attach(null); is it the same as if you just don't make any attach? That's probably why it is working!!

Upvotes: 0

Related Questions