Where is your N+1 issue?
Jul 14, 2022
28
Level 8
Excel Import, N+1 Issue
Hi, I need some help: I am using simple-excel package from spatie and I am able to import an excel document to the DB, the only caveat is that I am experiencing the N+1 problem when querying the import. Below is the store method of my controller:
public function store(Request $request)
{
$this->validate($request, [
'import_file' => 'required|mimes:xls,xlsx,csv'
]);
SimpleExcelReader::create($request->file('import_file'), 'xlsx')->getRows()
->each(function(array $rowProperties) {
$user= User::where('name', 'like', '%'. $rowProperties['username'].'%')->first();
Department::create([
'user_id' => $user->id,
'name' => $rowProperties['name'],
'code' => $rowProperties['code']
]);
});
return back()->with('success', 'All good!');
}
Kindly help me rewrite the code $user= User::where('name', 'like', '%'. $rowProperties['username'].'%')->first(); in a more effecient way.
Level 122
how often are you going to run this? - does it really matter?
1 like
Please or to participate in this conversation.