Exporting And Importing Data With Laravel Excel Package

Exporting and importing data is a common requirement in web applications. Laravel Excel is a popular package for handling exports and imports in Laravel. It provides a simple, expressive way to create and manage Excel and CSV exports and imports in your Laravel application.


In this blog, we will go through an example of how to use Laravel Excel to export data from a database table and import data into a database table.


Exporting Data

To export data from a database table, you first need to install the Laravel Excel package. You can do this by running the following command:

composer require maatwebsite/excel


Next, create a new controller and add the following code to it:

<?php

namespace App\Http\Controllers;

use App\User;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function export()
    {
        $users = User::all();

        Excel::create('users', function($excel) use($users) {
            $excel->sheet('Sheet 1', function($sheet) use($users) {
                $sheet->fromArray($users);
            });
        })->export('xls');
    }
}


This code fetches all the users from the users table and exports them to an Excel file. You can then use this Excel file to download or store the data.


Importing Data

To import data into a database table, you can use the import method provided by the Laravel Excel package. Add the following code to your controller:

public function import(Request $request)
{
    Excel::import(new UsersImport, $request->file('file'));

    return back()->with('success', 'Import successful');
}


This code imports the data from the uploaded file into the users table. You will need to create a new UsersImport class to handle the import. This class should implement the Importable interface and have a collection method:

<?php

namespace App\Imports;

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class UsersImport implements ToModel, WithHeadingRow
{
    public function model(array $row)
    {
        return new User([
            'name' => $row['name'],
            'email' => $row['email'],
            'password' => bcrypt($row['password']),
        ]);
    }
}


This class maps the data from the Excel file to the users table. The WithHeadingRow concern is used to specify that the first row of the Excel file contains the column headings.


That's it! You now have a basic example of how to use Laravel Excel to export and import data in your Laravel application. Laravel Excel provides many more features and customization options, so be sure to check out the documentation for more information.