I have a question, I've been developing laravel application and I encountered this strange error:
QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testenv`.`products`, CONSTRAINT `products_tenant_id_foreign` FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`)) (SQL: insert into `products` () values ())
and Here's my store function
public function store(Request $request)
{
$product = new Product;
/*
$product->name = $request->name;
$product->stockQty = $request->stockQty;
$product->minimumQty = $request->minimumQty;
$product->description = $request->description;
$product->notes = $request->notes;
$product->tenantMargin = $request->tenantMargin;
$product->length = $request->length;
$product->height = $request->height;
$product->weight = $request->weight;
$product->showLength = $request->showLength;
$product->showHeight = $request->showHeight;
$product->showWeight = $request->showWeight;
$product->size = $request->size;
$product->colorName = $request->colorName;
$product->colorHex = $request->colorHex;
$product->isActive =$request->isActive;
$product->tenant_id = $request->tenant_id;
$product->productviewid = $request->productviewid;
*/
$product->save($request->all());
return "product successfully created";
}
And the error only occurs if i use
$product->save($request->all());
but if I un-comment the the commented code and use
$product->save()
instead, it works, no error.
Can anyone help me to find the source of this problem?
Since you're not using the mass assignment feature, you should use $product->save();
here.
If you want to use the mass assignment, just do this:
public function store(Request $request)
{
Product::create($request->all());
}
As Alexey said, $product->save()
it's going to use the data sent in the function instead of whatever you've set before, just like what you are trying to do in your example.
That way you are not using the mass assignment feature, because you are specifying every single field that needs to be updated in the database.
$product->save($parameters)
actually makes use of the mass assignment feature and those attributes need to fillable, or un-guarded in the laravel properties.
Note that also Model::create()
supports mass assignments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With