PHP code example of sinemacula / laravel-resource-exporter
1. Go to this page and download the library: Download sinemacula/laravel-resource-exporter library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sinemacula / laravel-resource-exporter example snippets
// app/Http/Resources/UserResource.php
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use SineMacula\Exporter\Contracts\ProvidesTabularExport;
use SineMacula\Exporter\Http\Concerns\RespondsWithExports;
use SineMacula\Exporter\Schema\TabularSchema;
class UserResource extends JsonResource implements ProvidesTabularExport
{
use RespondsWithExports;
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
public function tabular(Request $request): TabularSchema
{
return new UserExportSchema($request);
}
}
// app/Exports/UserExportSchema.php
use SineMacula\Exporter\Schema\Column;
use SineMacula\Exporter\Schema\TabularSchema;
class UserExportSchema extends TabularSchema
{
public function columns(): array
{
return [
Column::make('id', 'ID'),
Column::make('name', 'Name'),
Column::make('email', 'Email'),
Column::make('created_at', 'Joined')->date('Y-m-d'),
Column::make('orders', 'Orders')->count(),
];
}
}
use SineMacula\Exporter\Schema\Column;
use Illuminate\Http\Request;
Column::make('salary', 'Salary')
->visible(static fn (Request $request): bool => $request->user()?->isAdmin() ?? false);
use SineMacula\Exporter\Facades\Exporter;
// Inline download response
return Exporter::collection(UserResource::collection($users))
->format('csv')
->download('users.csv');
// Store on a disk, get the path back
$path = Exporter::query(User::query()->where('active', true), UserResource::class)
->format('xlsx')
->store('s3', 'exports/users.xlsx');
// Raw string
$csv = Exporter::export(new UserResource($user))->format('csv')->toString();
use SineMacula\Exporter\ResourceExport;
Route::get('/users/export', function () {
return ResourceExport::forQuery(User::query(), UserResource::class)
->authorizeUsing(fn ($request) => $request->user()->can('export', User::class))
->paginatedJsonOrStreamedExport();
});