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

17,266

Solution 1

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

Solution 2

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.

Share:
17,266
Arga Aditya
Author by

Arga Aditya

Updated on June 05, 2022

Comments

  • Arga Aditya
    Arga Aditya almost 2 years

    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?