CasperSecurity
<?php
namespace App\Exports;
use App\Models\PayrollItems;
use App\Models\EmployeeRegistration;
use App\Models\SalaryCalculation;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Collection;
use Illuminate\Support\Carbon;
class SalaryFormatExport implements FromCollection,WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
protected $headings;
public $month;
public $year;
public function __construct()
{
$this->headings = $this->getPayrollItemsHeadings();
}
public function collection()
{
if(session('selected_month')==null){
$selectedMonth = session('selected_month', Carbon::now());
$this->month=Carbon::parse($selectedMonth)->format('m');
$this->year=Carbon::parse($selectedMonth)->format('Y');
}else{
$this->month=Carbon::parse(session('selected_month'))->format('m');
$this->year=Carbon::parse(session('selected_month'))->format('Y');
}
session()->forget('selected_month');
$employees=EmployeeRegistration::where('status',1)->get();
$payrollItems = PayrollItems::select('payroll_item_short_name')->distinct()->pluck('payroll_item_short_name')->toArray();
$data = new Collection();
foreach($employees as $emp){
$rowData = [
'employee_id' => $emp->employee_id,
'month' => $this->month,
'year' => $this->year,
'name'=>$emp->name
];
$salarydata=SalaryCalculation::where('id',$emp->id)
->where('month',$this->month)
->where('year',$this->year)
->get(['payroll_item_name', 'amount']);
foreach($payrollItems as $item){
$amount='0';
if(sizeof($salarydata)>0){
foreach($salarydata as $salary){
if($salary->payroll_item_name === $item){
$amount=$salary->amount;
break;
}
}
}
else{
$amount='0';
}
$rowData[$item] = $amount;
}
$data->push( $rowData);
}
// dd($data);
return $data;
}
public function headings(): array
{
return $this->headings;
}
private function getPayrollItemsHeadings()
{
$uniquePayrollItems = PayrollItems::select('payroll_item_short_name')->distinct()->pluck('payroll_item_short_name')->toArray();
$headings = ['employee_id', 'month', 'year','name'];
foreach ($uniquePayrollItems as $item) {
$headings[] = $item;
}
return $headings;
}
}