Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions app/Http/Controllers/CsvExport.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,44 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

class CsvExport extends Controller {
use App\Http\Requests\GenerateCSVRequest;
use Symfony\Component\HttpFoundation\StreamedResponse;

class CsvExport extends Controller
{
/**
* Converts the user input into a CSV file and streams the file back to the user
*/
public function convert()
public function convert(GenerateCSVRequest $request): StreamedResponse
{
return ['success' => false];
$tableItems = $request->get('tableItems');

$filename = 'items.csv';

$headers = [
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$filename",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
];

$columns = array_keys($tableItems[0]);

$callback = function () use ($tableItems, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);

foreach ($tableItems as $item) {
fputcsv($file, $item);
}

fclose($file);
};

return response()->stream($callback, 200, $headers);
}
}
33 changes: 33 additions & 0 deletions app/Http/Requests/GenerateCSVRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class GenerateCSVRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
'tableItems' => ['required', 'array'],
'tableItems.0' => ['required', 'array']
];
}
}
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"php": "^7.2",
"fideloper/proxy": "^4.0",
"laravel/framework": "^6.2",
"laravel/tinker": "^2.0"
"laravel/tinker": "^2.0",
"league/csv": "^9.7"
},
"require-dev": {
"facade/ignition": "^1.4",
Expand Down
Loading