How to Send data from Controllet to Import Multiple Sheet on Maatwebsite Laravel Excel Package?
To send data from a controller to Maatwebsite Laravel Excel Package for importing multiple sheets in a single Excel file, follow the steps below:
-
Install the required packages: Make sure you have the Maatwebsite Laravel Excel package installed in your project. If not, install it via composer:
composer require maatwebsite/excel
-
Create a new controller for handling the Excel import: Create a new controller, for example,
ImportController.php
, and define the necessary methods for handling the Excel import.namespace App\Http\Controllers; use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\WithMapping; use App\Imports\MyImport; class ImportController extends Controller { // ... }
-
Define the import method: Create a new import class, for example,
MyImport.php
, in theapp/Imports
directory. This class will handle the data mapping and validation.namespace App\Imports; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\WithValidation; use Maatwebsite\Excel\Validators\ValidationRule; class MyImport implements ToModel, WithHeadings, WithValidation { use Importable; protected $headings = [ 'column1', 'column2', // ... ]; protected $rules = [ 'column1' => ['required', 'string'], 'column2' => ['required', 'numeric'], // ... ]; public function model(array $row) { return new \App\Models\MyModel([ 'column1' => $row['column1'], 'column2' => $row['column2'], // ... ]); } }
-
Implement the controller method for handling the Excel import: In the
ImportController
, define a method for handling the Excel import request. This method will use theMyImport
class to process the data.namespace App\Http\Controllers; use Maatwebsite\Excel\Facades\Excel; use App\Imports\MyImport; class ImportController extends Controller { public function import() { Excel::import(new MyImport, request()->file('file')); return back()->with('success', 'Excel file imported successfully.'); } }
-
Create a route for the import method: Add a new route in the
routes/web.php
file for handling the Excel import request.Route::post('/import', 'ImportController@import')->name('import');
-
Handle the Excel file upload in the form: In your form view, add an input field for uploading the Excel file and a submit button. In the form action, use the
import
route.<form action="{{ route('import') }}" method="post" enctype="multipart/form-data"> @csrf <input type="file" name="file"> <button type="submit">Import</button> </form>
Now, when you submit the form with an Excel file, the data will be imported using the MyImport
class, and multiple sheets in the Excel file will be processed accordingly based on the defined headings and rules.