Excel Export File In Laravel

Anil Kumar Thakur
1 min readAug 26, 2023

install the package

composer require anil/file-export

Make one service class for exporting to use anywhere


use App\Models\User;
use App\Models\Post;
use Illuminate\Http\JsonResponse;
use ReflectionException;

/**
* Class ExportDataService
*/
class ExportDataService extends \Anil\FileExport\Service\ExportDataService
{

/**
* @throws ReflectionException
*/
public function exportPosts()
{
$builder = Post::query();// your builder
return $this->exportData(
builder: $builder,
header: Post::exportHeader(),
mapping: Post::exportHeaderMapping(),
);

}

/**
* @throws ReflectionException
*/
public function exportUsers()
{
$builder = User::query();// your builder

return $this->exportData(
builder: $builder,
header: User::exportHeader(),
mapping: User::exportHeaderMapping(),
);

}

Inside your model make two static functions for the header and data you want to export

<?php
namespace App\Models;


class Post extends Model

// ....

public static function exportHeader(): array
{
return [
'name',
'description',
//...your ramaining columns value to be exported as header item
];
}

public static function exportHeaderMapping(): Closure
{
return static function ($model) {
return [
$model->name,
$model->description,
//...your ramaining mapped columns value to be exported
];
};
}

Finally, a call from the controller

<?php

namespace App\Http\Controllers;
use App\Services\ExportDataService;

class UserController extends Controller
{

public function export(ExportDataService $exportDataService)
{
return $exportDataService->exportUsers();
}

The “anil/file-export” package offers a convenient solution for developers who frequently deal with exporting data. By abstracting the complexities of file creation and formatting, it simplifies the process and helps developers focus on delivering quality data to end-users. Whether you’re generating reports, sharing data, or performing data analysis, this package can be a valuable addition to your PHP toolkit.

--

--