skip to Main Content

I am trying to read an excel file in laravel using Maatwebsite

But I don’t want to store it in the database.

public function store(Request $request)
{
    $rules = array(
        'file' => 'required',
    );

    $request->validate($rules);

    try {
        Excel::import($request->file('file'), function ($reader) {

            foreach ($reader->toArray() as $key => $value) {
                echo $key;
            }
        });
    } catch (Exception $e) {
    }

}

The echo show empty. I did $request->get("file") and it displays my filename which shows that it is passing an excel file.

2

Answers


  1. try to create a import class like this:

    class UsersImport implements ToCollection
    {
        public function collection(Collection $rows)
        {
            foreach ($rows as $row) 
            {
                // simply use dd() or dump() here and then save it to db
                User::create([
                    'name' => $row[0],
                ]);
            }
        }
    }
    

    and then use it like this :

    Excel::import(new UsersImport, $request->file('file'));
    

    check this for more info :
    https://docs.laravel-excel.com/3.1/imports/collection.html

    Login or Signup to reply.
  2. first, create an import file using the command,

    php artisan make:import EmployeeImport
    

    This will create a file in the App/Imports

    Then in the controller function, for example

    use MaatwebsiteExcelFacadesExcel;
    
    $request->validate([
         'file' => 'required|file'
    ]);
    
    DB::beginTransaction();
     try {
        Excel::import(new EmployeeImport, $request->file('file'));
        DB::commit();
    } catch (MaatwebsiteExcelValidatorsValidationException $e) {
        $errors = $e->errors();
        DB::rollBack();
        return back()->withErrors($errors);
    } catch (Exception|error $exception) {
        DB::rollBack();
        Alert::error('Failed!!!', 'Something Went Wrong, Please try Again and Analyse the file first');
        return redirect()->back();
    }
    
    
    Alert::success('Uploaded', 'Uploaded successfully');
    return redirect() -> route('employees.index');
    

    and in the import file, you will have the function like this

    public function collection(Collection $collection)
    {
        foreach ($collection as $key => $row) {
           dd($row); 
     
    
        }
    }
    

    in the $row you will have all the data available.
    you can also use the model method.

    you can read in detail from here
    there are a lot of options where you can read and apply.

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