Search code examples
phpsqllaravellaravel-5laravel-5.3

Laravel save($request->all()) Error


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?


Solution

  • 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());
    }