Home > Enterprise >  Laravel Update Request Ignoring fields that don't exist from Request object
Laravel Update Request Ignoring fields that don't exist from Request object

Time:06-09

I'm sending this large object to the Laravel backend:

{
  field1: 'some value',
  field2: 213,
  field3: 123
}

And the PHP method to update looks something like this:

    public function update(OrderedItem $orderedItem, Request $request): JsonResponse
    {
        $orderedItem->update($request->body);

        return response()->jsonSuccess([
            'message' => 'Item updated',
            'item'    => $orderedItem
        ]);
    }

The issue is field3 doesn't exist for this model (OrderedItem). Is there a way for me to tell Laravel: 'Hey ignore the fields that don't match the table, just update the values that match'.

Current error:

message: "SQLSTATE[42703]: Undefined column: 7 ERROR:  column \"unit\" of relation \"ordered_items\" does not exist\nLINE 1: ...dered_items\" set \"created_at\" = $1, \"price\" = $2, \"unit\" = $...\n                                                             ^ (SQL: update \"ordered_items\" set \"created_at\" = 2022-06-04 21:29:25, \"price\" = 123, \"unit\" = {\"id\":\"6\",\"abbreviation\":\"g\",\"name\":\"gram\",\"plural\":\"grams\",\"display_order\":\"6\",\"additional_aliases\":\"gr, gm\"}, \"lead_times\" = {\"text\":\"7-10 days*\",\"value\":{\"shipping_lead_min_time\":7,\"shipping_lead_max_time\":10}}, \"spend_codes\" = [], \"selected_spend_code\" = -1, \"status_string\" = 1 Placed, \"price_float\" = 312, \"parts\" = [{\"id\":1,\"ordered_item_id\":1,\"quantity\":1,\"status\":2,\"packing_slip_id\":null,\"backorder_arrival_date\":null,\"return_reason\":null,\"canceled_by\":null,\"confirmation_number\":null,\"backorder_shipping_date\":null,\"inventory_item_id\":null,\"inventoried_by_user_id\":null,\"inventoried_at\":null,\"status_string\":\"Placed\",\"packing_slip\":null}], \"updated_at\" = 2022-06-02 21:29:25 where \"id\" = 1)"

CodePudding user response:

You should only update the specified fields, it helps your code become cleaner:

public function update(OrderedItem $orderedItem, Request $request): JsonResponse
    {
        $orderedItem->update($request->only(['field1', 'field2']));

        return response()->jsonSuccess([
            'message' => 'Item updated',
            'item'    => $orderedItem
        ]);
    }
  • Related