Search code examples
laraveltable-relationshipsexcel-import

Laravel maatwebsite import and fill a column with a select form


I'm using maatwebsite's Excel import library to import employees into a database table and it works quite well. However, on the View page where I select the Excel file to import, I have a select drop-down that shows data from the related Companies table, so that that specific selected Company is posted to all the currently imported employees' Comp_id foreign key. I have created the hasMany and belongsTo relations in the respective Company and Employee models.

The data sent in the EmployeeController:

public function viewImport()
{
    $employees = Employee::all(); 
    return view('viewImport', 
        ['companies' => Company::pluck('CompanyName', 'Comp_id')
        ])->withEmployees($employees);
}



 public function importExcel(Request $request)
 {

    if($request->hasFile('import_file')){
        $path = $request->file('import_file')->getRealPath();

        $data = Excel::load($path, function($reader) {})->get();

        $company = Company::.....; /*???????????????

        if(!empty($data) && $data->count()){

            foreach ($data->toArray() as $key => $value) {
                if(!empty($value)){ 
 foreach ($value as $v) {
     $insert[] = ['name'=> $v['name'],
                  'surname'=> $v['surname'],
                  'idno'=> $v['idno'],
                  'phone'=> $v['phone'],
                  'salary'=> $v['salary'],
                  'dob'=> $v['dob'],
                  'jobdescription'=> $v['jobdescription'],
                  'initials'=> $v['initials'],
                  'Comp_id' => .... /* ???????????????
                 ];

I've included the Company model as class in the EmployeeController.

I want to add a field insertion 'Comp_id' => .... with the Comp_id value of the selected drop-down. How do I create the $company variable in the function so that the selected Comp_id can be inserted for every row? Or is there a completely different way?

Thanks in advance.


Solution

  • Nailed it with 'comp_id' => $request->get('Comp_id').

    foreach ($data->toArray() as $key => $value) {
        if(!empty($value)){
            foreach ($value as $v) {        
                $insert[] = ['name'=> $v['name'],
                 'surname'=> $v['surname'],
                 'idno'=> $v['idno'],
                 'phone'=> $v['phone'],
                 'salary'=> $v['salary'],
                 'dob'=> $v['dob'],
                 'jobdescription'=> $v['jobdescription'],
                 'initials'=> $v['initials'],
                 'comp_id' => $request->get('Comp_id'),
                ];