I am working with Laravel 5.8 with PHP 7.4 to develop my project, and in this project, I wanted to make an Excel file out of a table called students
.
So here is what I did:
I typed composer require maatwebsite/excel
at the Terminal and downloaded the package.
I added \Maatwebsite\Excel\ExcelServiceProvider::class,
in providers
at config/app.php
, and 'Excel' => \Maatwebsite\Excel\Facades\Excel::class,
as aliases
.
Then I added this method to the Model Student.php
:
public static function getCustom()
{
$records = DB::table('students')->select('mbr_id','mbr_mobile','mbr_post_code','mbr_address','mbr_name','mbr_family','mbr_national_code','mbr_mobile','province','city','degree','grade');
return $records;
}
And then made this new Export file:
php artisan make:export StudentExport --model=App\Member\Student
And this file holds this:
use App\Member\Student;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\withHeadings;
class StudentExport implements FromCollection, withHeadings
{
public function headings(): array
{
return [
'Name',
'Family Name',
'National Code',
'Mobile Number',
'Province',
'City',
'Degree'
'Grade',
'Registered at',
];
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return collect(Student::getCustom());
}
}
And at the Controller, I have added these methods:
public function exportIntoExcel()
{
return Excel::download(new StudentExport, 'studentlist.xlsx');
}
public function exportIntoCSV()
{
return Excel::download(new StudentExport, 'studentlist.csv');
}
And also these routes to web.php
:
Route::get('export-excel','StudentAdminController@exportIntoExcel');
Route::get('export-csv','StudentAdminController@exportIntoCSV');
But when I try both of these routes, I get this as result:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Return value of Maatwebsite\Excel\Sheet::mapArraybleRow() must be of the type array, null returned
So what's going wrong here?
Update your modal
public static function getCustom()
{
$records = DB::table('students')->select('mbr_id','mbr_mobile','mbr_post_code','mbr_address','mbr_name','mbr_family','mbr_national_code','mbr_mobile','province','city','degree','grade')->get();
return $records;
}
In your export file
return Student::getCustom();