Skip to content
Advertisement

Why is this not saving to the database?

I’m trying to save a new product into the database, this product has exportation factors which i’m also trying to save, why is this not working?

 if ($request->has('export_factors')) {
    $exportationFactors = [];

    foreach ($request->get('export_factors') as $item) {
        if (key_exists('country_id', $item)) {
            $export = ExportationFactor::where('country_id', $item['country_id'])->first();
        } else if (key_exists('fi', $item)) {
            $export = ExportationFactor::where('fi', $item['fi'])->first();
        } else if (key_exists('margin', $item)) {
            $export = ExportationFactor::where('margin', $item['margin'])->first();
        }

        $export->save();

        $exportationFactors[] = [
            "product_id" => $export->product_id,
             "country_id" => $export->country_id,
             "fi" => $export->fi,
             "margin" => $export->margin
        ];

        if (count($exportationFactors) > 0) {
            ExportationFactor::insert($exportationFactors);
        }

    }
}

The error i’m getting is:

Call to a member function save() on null

on line $export->save();

Advertisement

Answer

Put the insert outside the loop for performance, and dont do a save on something that’s not there

$product_id = //you need to fill this one.
if ($request->has('export_factors')) {
    $exportationFactors = [];

    foreach ($request->get('export_factors') as $item) {
        $country_id = $item['country_id']??null;
        $fi = $item['fi']??null;
        $margin = $item['margin']??null;
        if (isset($fi, $margin, $country_id) {
            $exportationFactors[] = [
                "product_id" => $product_id,
                "country_id" => $country_id,
                "fi" => $fi,
                "margin" => $margin,
            ];
        }
    }
    if (count($exportationFactors)) {
        ExportationFactor::insert($exportationFactors);
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement