Laravel Excel Import: "Attempt to read property \"id\" on null"

545 Views Asked by At

I am trying to return the id from a relationship based on the excel that is uploaded. When I dd() the variable, the value shows:

enter image description here

Laravel Import

class ContactImport implements ToModel, WithHeadingRow, 
{
    use Importable;

    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        $industry_id = ContactIndustry::where("id", "=", $row['industry'])->first();
        $status_id   = ContactStatus  ::where("id", "=", $row['status'])->first();
        $type_id     = ContactType    ::where("id", "=", $row['type'])->first();
        $category_id = ContactCategory::where("id", "=", row['category'])->first();
        $user_id     = User           ::where("id", "=", $row['user'])->first();

        return new Contact([
            'name'         => $row['name'],
            'address'      => $row['address'],
            'industry_id'  => $industry_id->id,
            'status_id'    => $status_id->id,
            'type_id'      => $type_id->id,
            'category_id'  => $category_id->id,
            'remark'       => $row['remark'],
            'user_id'      => $user_id->id,
        ]);
    }
}

enter image description here

@Controller

public function import(Request $request)
{
    (new ContactImport)->import($request->file('file'), 'local', Maatwebsite\Excel\Excel::XLSX);
    
        return response()->json([
            'status' => true,
            'message' => 'Successfully import Contact ',
        ]);
}

enter image description here

Update I tried hard coding it to see if the code works. It works, but apparently I am importing an extra 7 rows of data that I am not sure from coming where, so that's where the null value is coming.

So I implement the SkipEmptyRows and now it works. Still hope someone can explain whats the problem. Thanks.

0

There are 0 best solutions below