eya
eya

Reputation: 55

Laravel - Undefined index

What I am trying to do is to add an expense and a vendor in the same time knowing that the relation between expenses table and vendors table is a one to many relation .. A vendor can have vendor_contacts which is a table that have a one to many relation with vendors table ..

This is my code :

if (isset($data['vendor'])) {
            $canSaveVendor = false;
            $vendorPublicId = array_get($data, 'vendor.public_id') ?: array_get($data, 'vendor.id');
            if (empty($vendorPublicId) || $vendorPublicId == '-1') {
                $canSaveVendor = Auth::user()->can('create', ENTITY_VENDOR);
            } else {
                $vendor = Vendor::scope($vendorPublicId)->first();
            }
            if ($canSaveVendor) {
                $vendor = $this->vendorRepo->save($data['vendor']);
            }
            if ($canSaveVendor) {
                $data['vendor_id'] = $vendor->id;
            }
        }
        $expense = $this->expenseRepo->save($data, $expense);
        $vendor = $expense->vendor;
        $vendor->load('vendor_contacts');

        return $expense; 

This is the code to execute when we want to save a vendor :

if ($vendor) {
            // do nothing
        } elseif (!$publicId || $publicId == '-1') {
            $vendor = Vendor::createNew();
        } else {
            $vendor = Vendor::scope($publicId)->with('vendor_contacts')->firstOrFail();
            \Log::warning('Entity not set in vendor repo save');
        }

        $vendor->fill($data);
        $vendor->save();

        $first              = true;
        $vendorcontacts     = isset($data['vendor_contact']) ? [$data['vendor_contact']] : $data['vendor_contacts'];

        foreach ($vendorcontacts as $vendorcontact) {
            $vendorcontact      = $vendor->addVendorContact($vendorcontact, $first);
            $first              = false;
        }

when I try to save itsaves correctly the vendor in vendors table ,but neither the expense no the vendor_contacts and it gives me Undefined index: vendor_contacts what should I do please ?

Upvotes: 4

Views: 1923

Answers (1)

Filip Koblański
Filip Koblański

Reputation: 10018

You made mistake here:

$vendorcontacts = isset($data['vendor_contact']) 
    ? [$data['vendor_contact']] 
    : $data['vendor_contacts'];

try like this:

$vendorcontacts = isset($data['vendor_contact']) 
    ? [$data['vendor_contact']] 
    : [];

Upvotes: 2

Related Questions