Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

konrms's avatar

How to export database table to excel file in laravel

Hi guys.

I'm trying to export the table "formal", to a simple excel file. I have installed the packet necessary with "composer require maatwebsite/excel" command from cmd and also have edited my app.php file adding "Maatwebsite\Excel\ExcelServiceProvider::class," to providers and "'Excel' => Maatwebsite\Excel\Facades\Excel::class," to aliases.

My blade successfully shows "formal" as html. Now I have added a second button with export to excel option. Unfortunately, I'm getting an error "Call to undefined method Maatwebsite\Excel\Excel::create()" when pressing "Download excel button".

Could you help me please?

This is my blade with the "Download excel" button added.

<!DOCTYPE html>
<html lang="el">
<head>
    <meta charset="UTF-8">
    <title>Program</title>
	
</head>
<body>

<b>Programme: {{ $key }}</b>
<br>
<br>

<table border="1">
    <tr>
        <th>Column1</th>
        <th>Column2</th>
		...
		...
        <th>Column n</th>
    </tr>
    @foreach($star as $v2)
    <tr>
        <th>{{ $v2->category }}</th>
        <td>{{ $v2->code }}</td>
        <td>{{ $v2->title }}</td>
		...	   
		...

	<td>{{ $v2->... }}</td>
    </tr>
    @endforeach
</table>
<br>


<form action = '/excel'>
	<input type="submit" value="Download excel">
<form>


<form action ='/programma'>
    <input type="submit" value="New Search" />
</form>


</body>
</html>

This is the ExportExcelController:

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;  

class ExportExcelController extends Controller
{
	public function excel()
	{
		$formal_data = DB::table('formal')->get()->toArray();
		$programma_array[] = array('category', 'code', 'title', 'dep', 'pms',
		.....);
			
		foreach($formal_data as $pass)
		{
			$programma_array[] = array
			(
			'category'  => $pass->category,
			'code'   => $pass->code,
			'title'    => $pass->title,
				....
      		);
			
		}
		
			
			Excel::create('Programma_Data', function($excel) use ($programma_array)
			{
				$excel->setTitle('Apotelesmata');
				$excel->sheet('Programma_Data', function($sheet) use ($programma_array)
				{
					$sheet->fromArray($programma_array, null, 'A1', false, false);
				});
			}) -> download('xlsx');
			
	        
    }
			   
}		

And my web.php

Route::get('/excel', 'ExportExcelController@excel')->name('export_excel.excel');
0 likes
14 replies
aurawindsurfing's avatar

Hi,

I use this package and it works perfectly.

It seems like you are trying to use the facade: https://docs.laravel-excel.com/3.1/architecture/#facade but that still requires you to call an exporter class that you need to create:

Try to follow this quick start guide: https://docs.laravel-excel.com/3.1/exports/

Create an export class in app/Exports You may do this by using the make:export command.

php artisan make:export UsersExport --model=User

The file can be found in app/Exports:

.
├── app
│   ├── Exports
│   │   ├── UsersExport.php
│ 
└── composer.json

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

<?php

namespace App\Exports;

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

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}

In your controller you can call this export now:

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;

class UsersController extends Controller 
{
    public function export() 
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
}

Find your users.xlsx in your downloads folder!

Hope it will help you!

1 like
JorickL's avatar

It looks like that your <form> doesn't provide the correct method to reach the controller. First of all, it looks like a simple GET request to me and it would be a normal link; no form required.

What happens when you type in the URL directly into the addresbar of your browser?

1 like
aurawindsurfing's avatar

@KONRMS - as @jorickl said - first establish if your export works if your form works separately. Just make a test route to controller method and see it the export part works.

1 like
konrms's avatar

@JORICKL - Hi Jorickl and @aurawindsurfing !

I replaced post with get at my web.php as below.

Route::get('/exagogi', 'FormalController@exporting');

When testing this case, I get error too as below (even if I directly enter http://laravel.site/exagogi: into browser line).

C:\xampp\htdocs\laravel\app\Exports\FormalExport.php
<?php
 
namespace App\Exports;
 
use App\formal;
use Maatwebsite\Excel\Concerns\FromCollection;
 
class FormalExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return formal::all();
    }
}
 
Arguments
"Class 'App\formal' not found"

My FormalController.php is the following. If I uncomment return ('Hello'); line and comment return Excel::download(new FormalExport, 'formal.xlsx'); I get Hello message as expected.

<?php namespace App\Http\Controllers;

use App\Exports\FormalExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request; 



class FormalController extends Controller
    {
        public function exporting() 
        {
            //return ('Hello!');
        return Excel::download(new FormalExport, 'formal.xlsx');
        }
    }       
JorickL's avatar

Please be consistent with lower- and uppercase. Classnames should be CamelCase and thus have a Capital letter at the beginning. Fix that, make sure you've imported the (right) classes and try again.

konrms's avatar

@JORICKL - For being on the safe side, I renamed formal table to users table in my database and query and retested everything. Now when pressing the export to excel button I get an empty page. I searched my pc for the users.xlsx file (which was supposed to be created in my downloads folder) but nothing was found anywhere.

I followed these two guides step by step: https://docs.laravel-excel.com/3.1/getting-started/installation.html https://docs.laravel-excel.com/3.1/exports/.

Could you help me with my code please? I have all necessary items below.

The blade excerpt is below:

<form action='/exagogi'>
    <input type="submit" value="Export to excel" />
</form>

My web.php excerpt is this:

Route::get('/exagogi', 'UsersController@export');

My whole UsersController is this:

<?php namespace App\Http\Controllers;

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;


class UsersController extends Controller
{
        
    public function export()
    {
        //return ('Trying to add export to excel function!');
        Excel::download(new UsersExport, 'users.xlsx');
    }
    
}       

and my app\Exports\UsersExport is below:

<?php

namespace App\Exports;

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

class UsersExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }
}
JorickL's avatar

Well, first of all, you're not returning anything in UsersController export() method. Try to find out the source. What happens if you dd(new UsersExport); in your export method? Does it initiate a new UsersExport class? And what happens if you dd((new UsersExport)->collection);? Does it return an Eloquent Collection with all users? And if nothing is working, just die('Export Method on UsersController called'); on the export method to literally see the methods fail...

Apparantly, the missing 'method="GET"' on your form is OK, because it reaches the UsersController, I suppose?

For what I can see now, it should work OK...

konrms's avatar

@JORICKL - Thank you very much! I should also thank @aurawindsurfing too.

Well I just managed to export to excel! After many many tests and failures.

But there is one thing left... I want my exported excel to have title in every table field on top and not only the table data copied into sheet. Any idea is very welcome!

For your info, my code is the following (for the whole solution, of course there should be applied these prerequisites too https://docs.laravel-excel.com/3.1/exports/).

https://docs.laravel-excel.com/3.1/getting-started/installation.html :

  1. web.php:
Route::get('/exagogi','UsersController@export');
  1. UsersExport.php (App\Exports\UsersExport.php)
<?php

namespace App\Exports;

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

class UsersExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }
}
  1. UsersController.php
<?php namespace App\Http\Controllers;

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UsersController extends Controller 
{
    public function export() 
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
}
konrms's avatar
konrms
OP
Best Answer
Level 1

Guys, I did it on the whole. So the total solution is below:

  1. web.php
Route::get('/exagogi','UsersController@export');
  1. UsersExport.php (App\Exports\UsersExport.php)
<?php

namespace App\Exports;

use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings; 

class UsersExport implements FromCollection, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }

    public function headings(): array
    {
        return [
            'Category',
            'Title',
            'Department'
        // etc


        ];
    }
}
  1. UsersController.php
<?php namespace App\Http\Controllers;

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UsersController extends Controller 
{
    public function export() 
    {
        return Excel::download(new UsersExport, 'result.xlsx');
    }
}
2 likes
Rhynel's avatar

How to implement with download batch parameter?

Please or to participate in this conversation.