File: /var/www/vhost/disk-apps/comfama.sports-crowd.com/app/Http/Controllers/Exports/ReportResults.php
<?php
namespace App\Http\Controllers\Exports;
use App\HeaderValue;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ReportResults implements FromCollection, WithHeadings, WithEvents
{
private $formId, $fromDate, $toDate;
public function __construct($formId, $fromDate, $toDate)
{
$this->formId = $formId;
$this->fromDate = $fromDate;
$this->toDate = $toDate;
}
// set the headings
public function headings(): array
{
$obj = HeaderValue::select('id', 'form_id', 'user_id', 'created_at')
->where('form_id', $this->formId)
->with('form', 'user', 'user.documentType', 'header_value_details')
->get();
$data = [];
if (count($obj) > 0) {
foreach ($obj as $header) {
$headers = array(
__('messages.answers.title_3'),
__('messages.answers.title_4'),
__('messages.answers.title_21'),
__('messages.answers.document_type'),
__('messages.answers.document'),
__('messages.answers.title_7'),
);
if (count($header->header_value_details) > 0) {
foreach ($header->header_value_details as $item) {
$headers[] = $item->field->name;
}
}
$data[] = $headers;
break;
}
}
return $data;
}
// freeze the first row with headings
public function registerEvents(): array
{
return [];
}
public function collection()
{
$fromDate = $this->fromDate;
$toDate = $this->toDate;
$obj = HeaderValue::select('id', 'form_id', 'user_id', 'created_at')
->where('form_id', $this->formId)
->where(function ($query) use ($fromDate, $toDate) {
if ($fromDate && $toDate) {
$query->whereBetween('created_at', [$fromDate . " 00:00:00", $toDate . " 23:59:59"]);
}
})
->with('form', 'user', 'user.documentType', 'header_value_details')
->get();
$data = [];
if (count($obj) > 0) {
foreach ($obj as $header) {
$headers = array(
$header->form->name,
$header->user->first_name . ' ' . $header->user->last_name,
$header->user->email,
$header->user->documentType ? $header->user->documentType->name : '',
$header->user->document,
\Carbon\Carbon::parse($header->created_at)->format('Y-m-d h:i:s A')
);
if (count($header->header_value_details) > 0) {
foreach ($header->header_value_details as $item) {
$headers[] = $item->value;
}
}
$data[] = $headers;
}
}
return collect($data);
}
}