Search code examples
laravellaravel-excel

How to import multiple rows from excel in laravel?


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

My code in imports:

<?php

namespace App\Imports;

use App\Models\LeadDetails;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class LeadsImport implements ToModel, WithHeadingRow
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|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


Solution

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

    class LeadsImport implements ToCollection