alphal
alphal

Reputation: 149

Laravel Maatwebsite excel

I need your help. I don't know how to import the excel file. I mean I don't understand where to put this users.xlsx and how to get its directory

 public function import()
        {
            Excel::import(new UsersImport, 'users.xlsx');

            return redirect('/')->with('success', 'All good!');
        }

Upvotes: 0

Views: 567

Answers (1)

Farshad
Farshad

Reputation: 2000

its simple on mattwebsite you need a controller like below :

  public function importExcel(Request $request)
{
    if ($request->hasFile('import_file')) {
        Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
            foreach ($reader->toArray() as $key => $row) {
// note that these fields are completely different for you as your database fields and excel fields so replace them with your own database fields
                $data['title'] = $row['title'];
                $data['description'] = $row['description'];
                $data['fax'] = $row['fax'];
                $data['adrress1'] = $row['adrress1'];
                $data['telephone1'] = $row['telephone1'];
                $data['client_type'] = $row['client_type'];


                if (!empty($data)) {
                    DB::table('clients')->insert($data);
                }
            }
        });
    }

    Session::put('success on import');

    return back();
}

and a view like this :

                <form
                  action="{{ URL::to('admin/client/importExcel') }}" class="form-horizontal" method="post"
                  enctype="multipart/form-data">
                {{ csrf_field() }}
                <div class="form-group">
                    <label class="control-label col-lg-2">excel import</label>
                    <div class="col-lg-10">
                        <div class="uploader"><input type="file"  name="import_file" class="file-styled"><span class="action btn btn-default legitRipple" style="user-select: none;">choose file</span></div>
                    </div>
                </div>
                <button class="btn btn-primary">submit</button>
            </form>

and finally a route like below :

Route::post('admin/client/importExcel', 'ClientController@importExcel');

Upvotes: 2

Related Questions