M.Pratheep
M.Pratheep

Reputation: 71

can I use eloquent model in foreach loop

foreach ($rows as $row) {
            $source = Inventory_sources::where('code', $row['inventory_source_code'])->first();
            $source_id=$source->id;
            $product = Product::create([
                'type' => $row['type'],
                'sku' => $row['sku'],
                'attribute_family_id' => $row['attribute_family'],
            ]);
            product_flat::create([
                'product_id' => $product->id,
                'sku' => $row['sku'],
                'name' => $row['name'],
                'price' => $row['price'],
                'status' => $row['status'],
            ]);
            product_inventories::create([
                'inventory_source_id' => $source_id,
                'product_id' => $product->id,
                'qty' => $row['qty'],
            ]);
        }

error - Trying to get property 'id' of non-object I try dd() its show the output. how to resolve this issue

Upvotes: 2

Views: 763

Answers (2)

Dilip Hirapara
Dilip Hirapara

Reputation: 15306

This error you're getting because while add condition code = $row['inventory_source_code'] sometime you're not getting records.

So you need to check the condition.

foreach ($rows as $row) {
    $source = Inventory_sources::where('code', $row['inventory_source_code'])->first();
    if(!empty($source)){
        $source_id=$source->id;
        //your entire logic. 
    }
}

Upvotes: 1

OMR
OMR

Reputation: 12208

your problem is that the $source variable could be sometimes null,

you must avoid use $source->id; when the $source is null

 $source = Inventory_sources::where('code',
$row['inventory_source_code'])->first();

if($source!=null)
{
// write the suitable code here ...
}

Upvotes: 1

Related Questions