skip to Main Content

I want to import multiple rows of an excel file into database in laravel.

My code in imports:

<?php

namespace AppImports;

use AppModelsLeadDetails;
use MaatwebsiteExcelConcernsToModel;
use IlluminateSupportFacadesHash;
use MaatwebsiteExcelConcernsWithHeadingRow;

class LeadsImport implements ToModel, WithHeadingRow
{
    /**
     * @param array $row
     *
     * @return IlluminateDatabaseEloquentModel|null
     */
    public function model(array $rows)
    {
        // dd($rows);
        foreach ($rows as $row) {
                return new LeadDetails([
                    // "lead_id" => $lead_id,
                    "full_name" => $row['name'],
                    "student_email" => $row['email'],
                    "phone_number" => $row['contact'],
                    "work_location" => $row['work_location'],
                    "phone_number" => $row['contact'],
                    "lead_apply_date" => $row['date'],
                    "lead_remarks" => $row['remark'],
                ]);
        }
    }
}

controller function:

public function uploadLeadExcel(Request $request)
    {
        Excel::import(new LeadsImport, $request->file);
        return response()->json([
            'message'=>'success',
            'status'=>201
        ]);
    }

When hitting from postman an error appears telling ‘undefined offset name in file . Please help

2

Answers


  1. Chosen as BEST ANSWER

    ok now its working. I have installed laravel excel according to documentation and used

    class LeadsImport implements ToCollection
    

  2. Because $row doesn’t have a key ‘name’. Try:

    return new LeadDetails([
        // "lead_id" => $lead_id,
        "full_name" => $row['name'] ?? '',
        "student_email" => $row['email'] ?? '',
        "phone_number" => $row['contact'] ?? '',
        "work_location" => $row['work_location'] ?? '',
        "phone_number" => $row['contact'] ?? '',
        "lead_apply_date" => $row['date'] ?? '',
        "lead_remarks" => $row['remark'] ?? '',
    ]);
    

    You should modify lead_id column of the table to auto increment

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search