Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel unable to update field to null

I can't figure out how to set a field to null on certain condition. It should be an easy query but I'n not able to set the right value for NULL on a nullable field.

Product::where('id', $product_list)->update(['family_id' => null]);

nor

Product::where('id', $product_list)->update(['family_id' => DB::raw(null)]);

did the trick. Both cases compiled fine but the generated query seems to be wrong because I get a SQL error. In the irst case the error is :

SQLSTATE[HY093]: Invalid parameter number (SQL: update `products` set `family_id` = ?, `products`.`updated_at` = 2019-11-12 08:41:07 where `id` = ?)

and the error for the second one is :

QLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ', `products`.`updated_at` = ? where `id` = ?' at line 1 (SQL: update `products` set `family_id` = , `products`.`updated_at` = 2019-11-12 08:21:50 where `id` = ?)

In the first case it seems that NULL is not being added to the parameters to the prepared query, and in the secon the NULL value is being inserted as nothing in the query. There is any simple way to set the value to NULL?

like image 281
Carlos Mora Avatar asked Oct 20 '25 04:10

Carlos Mora


1 Answers

You should consider the following things first.

1) family_id column is nullable in your table. if not then set nullable.

2) Make sure you have in $fillable property of Product model column family_id.

Make sure $product_list returns id of that particular product. if $product_list is collection/array of product data then use like:

Product::where('id', $product_list->id)->update(['family_id' => null]);
like image 111
Amit Senjaliya Avatar answered Oct 22 '25 03:10

Amit Senjaliya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!