In your import, you need to check what do you have in your $row does it includes headers? You cannot just use it like json_encode
Maybe this will be better of:
return new Customer($row);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Importing excel sheet with dynamic data:
I have this issue
SQLSTATE[HY000]: General error: 1364 Field 'CustomerName' doesn't have a default value (SQL: insert into `customers` (`updated_at`, `created_at`) values (2020-01-21 14:27:59, 2020-01-21 14:27:59))
I want to importing data dynamically take the fields from excel sheet(title+data) columns
this is the code
this is the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = [
'CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country',
];
}
this is the controller code:
<?php
namespace App\Http\Controllers;
use App\Customer;
use App\Exports\CustomerExport;
use App\Imports\CustomerImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
class CustomerController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$customers = Customer::all();
return view('customer')->with('customers', $customers);
}
/**
* Import function
*/
public function import(Request $request)
{
if ($request->file('imported_file')) {
Excel::import(new CustomerImport(), request()->file('imported_file'));
return back();
}
}
/**
* Export function
*/
public function export()
{
return Excel::download(new CustomerExport(), 'customers.xlsx');
}
}
this is the import code :
<?php
namespace App\Imports;
use App\Customer;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class CustomerImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Customer([
'data' => json_encode($row),
]);
}
}
this is the export:
<?php
namespace App\Exports;
use App\Customer;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class CustomerExport implements FromCollection, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return Customer::all();
}
public function headings(array $row): array
{
return[
'data' => json_encode($row),
];
}
}
I don't know how to fix it
Please or to participate in this conversation.