Laravel 10 provides an easy and efficient way to import and export Excel and CSV files using the Laravel Excel package. This package makes it possible to manipulate Excel and CSV files effortlessly in Laravel applications. In this article, we will explore how to import and export Excel and CSV files in Laravel 10 using the Laravel Excel package with examples.
Step 1: Installing Laravel Excel Package
The first step to import and export Excel and CSV files in Laravel 10 is to install the Laravel Excel package. This package can be installed via composer by running the following command in your terminal:
composer require maatwebsite/excel
Once the package is installed, Laravel will automatically discover it.
Step 2: Creating the Import/Export Classes
Next, we will create the Import and Export classes to handle the import and export processes. We can use the php artisan make:import
and php artisan make:export
Artisan commands to generate the classes.
For example, to generate an import class for a Users
model, we can run the following command:
php artisan make:import UsersImport --model=Users
This will create a UsersImport
class in the app/Imports
directory, which extends the Maatwebsite\Excel\Concerns\ToModel
class. We can use this class to import data from an Excel or CSV file and save it to the Users
model.
Similarly, to generate an export class for the Users
model, we can run the following command:
php artisan make:export UsersExport --model=Users
This will create a UsersExport
class in the app/Exports
directory, which extends the Maatwebsite\Excel\Concerns\FromQuery
class. We can use this class to export data from the Users
model to an Excel or CSV file.
Step 3: Importing Data from Excel or CSV
To import data from an Excel or CSV file, we will need to create a route to handle the import process. Here is an example of how to create a route for importing data from a CSV file:
use App\Imports\UsersImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
Route::post('/import-users', function (Request $request) {
$file = $request->file('file');
Excel::import(new UsersImport, $file);
return redirect()->back()->with('success', 'Data imported successfully!');
})->name('import.users');
In the above code, we have created a route that accepts a file upload with the name file
. The uploaded file is then imported using the Excel::import
method, which takes the UsersImport
class and the file as parameters. Once the import process is completed, we redirect back to the previous page with a success message.
Step 4: Exporting Data to Excel or CSV
To export data to an Excel or CSV file, we will need to create a route to handle the export process. Here is an example of how to create a route for exporting data to an Excel file:
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
Route::get('/export-users', function () {
return Excel::download(new UsersExport, 'users.xlsx');
})->name('export.users');
In the above code, we have created a route that generates an Excel file using the UsersExport
class and the Excel::download
method. The downloaded file will have the name users.xlsx
.
Step 5: Using Queues for Large Data
When dealing with large data sets, the import and export processes can take a long time and use up a lot of server resources. To avoid this, we can use Laravel queues to handle the processes in the background. Here is an example of how to use queues for importing data:
use App\Imports\UsersImport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Queue;
use Maatwebsite\Excel\Facades\Excel;
Route::post('/import-users', function (Request $request) {
$file = $request->file('file');
Queue::push(new UsersImport($file));
return redirect()->back()->with('success', 'Data imported successfully!');
})->name('import.users');
In the above code, we have used the Queue::push
method to push the import process to a queue, which will handle the process in the background.
Step 6: Adding Validation
To ensure that the imported data is valid, we can add validation rules to the import class. Here is an example of how to add validation rules to the UsersImport
class:
use App\Models\Users;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToCollection;
class UsersImport implements ToCollection
{
public function collection(Collection $rows)
{
Validator::make($rows->toArray(), [
'*.email' => ['required', 'email', 'unique:users,email'],
'*.name' => ['required'],
])->validate();
foreach ($rows as $row) {
Users::create([
'name' => $row[0],
'email' => $row[1],
]);
}
}
}
In the above code, we have used the Validator
class to validate the email and name fields. If the validation fails, an exception will be thrown, which will prevent the import process from continuing.
Step 7: Adding Headers
To specify headers for the imported or exported data, we can add the WithHeadings
interface to the import or export class. Here is an example of how to add headers to the UsersExport
class:
use App\Models\Users;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class UsersExport implements FromQuery, WithHeadings
{
use Exportable;
public function headings(): array
{
return [
'Name',
'Email',
];
}
public function query()
{
return Users::query();
}
}
In the above code, we have added the WithHeadings
interface and defined the headers for the exported data using the headings
method.
Conclusion
In this article, we have explored how to import and export Excel and CSV files in Laravel 10 using the Laravel Excel package with examples. We have gone through the steps to install the package, create the import and export classes, import data from Excel or CSV, export data to Excel or CSV, use queues for large data, add validation rules, and add headers. With the Laravel Excel package, importing and exporting data in Laravel 10 has become an effortless process.