How to Export in Excel and CSV in Laravel

To export data in Excel and CSV in Laravel, use the maatwebsite/excel 3.1″ package. Laravel Excel package is intended at being Laravel-flavoured PhpSpreadsheet: a simple but elegant wrapper around PhpSpreadsheet to simplify the exports and imports. PhpSpreadsheet is a library written in pure PHP and provides a set of classes that allow us to read from and write to different spreadsheet file formats, like Excel and LibreOffice Calc.

Here are the steps to export data in Excel and csv in Laravel:

Step 1: Installation of package

Require the following package in the composer.json of your Laravel project. The following command will download the package and PhpSpreadsheet.

composer require maatwebsite/excel

Step 2: Configure the package

The Maatwebsite\Excel\ExcelServiceProvider is auto-discovered and registered by default.

If you want to register by yourself, then add the ServiceProvider in config/app.php:

'providers' => [
    /*
     * Package Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]

The Excel facade is auto-discovered.

To add it manually, add a Facade in config/app.php:

'aliases' => [
    ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]

If you want to publish a config, run the vendor publish command:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

This will create the new config file named config/excel.php.

Step 3: Create model and migration files

Type the following command.

php artisan make:model Disneyplus -m

Go to the [timestamp].create_disneypluses_table.php file and add the columns.

public function up(): void
{
        Schema::create('disneypluses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('show_name');
            $table->string('series');
            $table->string('lead_actor');
            $table->timestamps();
        });
}

Migrate the database using the following command.

php artisan migrate

Step 4: Create a controller and routes

The next step is to create a DisneyplusController.php file.

php artisan make:controller DisneyplusController

Add the two routes inside the routes >> web.php file.

// web.php

Route::get('disneyplus', 'DisneyController@create')->name('disneyplus.create');
Route::post('disneyplus', 'DisneyController@store')->name('disneyplus.store');

Create two methods inside the DisneyplusController.php file.

<?php

// DisneyplusController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Disneyplus;

class DisneyplusController extends Controller
{
    public function create()
    {

    }

    public function store()
    {
        
    }
}

Step: 5 Create a form blade file for input the data

Inside the views folder, create the form.blade.php file. Add the following code.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Disneyplus Shows
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('disneyplus.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name"/>
          </div>
          <div class="form-group">
              <label for="price">Series :</label>
              <input type="text" class="form-control" name="series"/>
          </div>
          <div class="form-group">
              <label for="quantity">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Show</button>
      </form>
  </div>
</div>
@endsection

Step 6: Store data in the database

We will write the two functions inside the DisneyplusController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Disneyplus;

class DisneyplusController extends Controller
{
    public function create()
    {
        return view('form');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }
}

So, in the above file, first, we have shown the form file, and then inside the store function, we check for validation and store the data in the database.

Add the fillable fields inside the Disneyplus.php model file.
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Disneyplus extends Model
{
    protected $fillable = ['show_name', 'series', 'lead_actor'];
}

Go to this route: http://laravel6.test/disneyplus or http://localhost:8000/disneyplus.

You will see one form. Try to save the data, and if everything in the code is right, you will see one entry in the database.

Step: 7 Create a view file to display the data.

Before creating a view file, we need to add one route inside the web.php.

// web.php

Route::get('disneyplus/list', 'DisneyplusController@index')->name('disneyplus.index');

Create a view file called list.blade.php file. Add the following code.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Add the code inside the index() function of the DisneyplusController.php file.

public function index()
{
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
}

Go to http://laravel6.test/disneyplus/list or http://localhost:8000/disneyplus/list.

You will see the listing of the shows.

Step 8: Create Exports class

You may do this by using the make:export command.

php artisan make:export DisneyplusExport --model=Disneyplus

The file can be found in app/Exports directory.

The file DisneyplusExport.php is the following.

<?php

namespace App\Exports;

use App\Disneyplus;
use Maatwebsite\Excel\Concerns\FromCollection;

class DisneyplusExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Disneyplus::all();
    }
}

If you prefer to create the export manually, you can build the following in app/Exports.

Step 9: Write the export function

Inside the DisneyplusController.php file, add the following code.

// DisneyplusController.php

use App\Disneyplus;
use App\Exports\DisneyplusExport;
use Maatwebsite\Excel\Facades\Excel;

public function export() 
{
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
}

Our final file looks like below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Disneyplus;
use App\Exports\DisneyplusExport;
use Maatwebsite\Excel\Facades\Excel;

class DisneyplusController extends Controller
{
    public function create()
    {
        return view('form');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }

    public function index()
    {
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
    }

    public function export() 
    {
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
    }
}

Finally, add the route to be able to access the export:

// web.php

Route::get('export', 'DisneyplusController@export');

Also, add the link to the Export inside the list.blade.php file.

@foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
      <td><a href="{{action('DisneyplusController@export')}}">Export</a></td>
    </tr>
@endforeach

Eventually, go to http://laravel6.test/disneyplus/list, and now you can see one link called Export.

Click on the Export link, and you will see the disney.xlsx file inside your Download folder.

Exporting collections in CSV in Laravel

By default, the export format is determined by the file’s extension.

public function export() 
{
   return Excel::download(new DisneyplusExport, 'disney.csv');
}

It will download the CSV file.

If you want to configure the export format explicitly, you can pass it through as 2nd parameter.

You can find more details about exporting in different formats on this link.

That’s it.

6 thoughts on “How to Export in Excel and CSV in Laravel”

  1. Can I export custom data from my table in my sql? in your example, you export all of data from DisneyPlus table, is it possible if I just export data from DisneyPlus with condition?

    Reply
  2. Hello,

    I have follow the same step but getting issue

    Unable to resolve NULL driver for [Maatwebsite\Excel\Transactions\TransactionManager].

    Reply
  3. Hi Krunal,
    I like your step by step tutorial. I am new to coding. When I was practicing, everything was smooth, but faced error after adding following line.

    Export

    Error:
    InvalidArgumentException
    Action DisneyplusController@export not defined. (View: C:\xampp\htdocs\Laravel7CRUD\resources\views\list.blade.php)

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.