CasperSecurity
<?php
namespace App\Exports;
use App\Models\EmployeeWageDetailsModel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Carbon\Carbon;
class EmployeeWageExport implements FromCollection,WithHeadings
{
protected $month;
protected $year;
/**
* Constructor to accept month and year (optional)
*/
public function __construct($month = null, $year = null)
{
// If month/year is null, calculate the previous month and year
if (!$month || !$year) {
$previousMonth = Carbon::now()->subMonth();
$this->month = $previousMonth->format('m'); // Get previous month (01-12)
$this->year = $previousMonth->format('Y'); // Get previous year
} else {
$this->month = $month;
$this->year = $year;
}
}
/**
* Return the collection of rows based on the month and year
* @return \Illuminate\Support\Collection
*/
public function collection()
{
// Fetch the distinct employees for the given month and year
$data = EmployeeWageDetailsModel::where('month', $this->month)
->where('year', $this->year)
->distinct('name', 'sub') // Ensures uniqueness based on name and sub
->get(['name', 'sub', 'father_name', 'designation', 'paid_days', 'extra_duty',
'rate_of_wage', 'gross_pay', 'extra_wages',
'epf', 'esic', 'total_deduction', 'net_pay', 'signature']); // Fetch only the required columns
// Add empty values for other columns in the database schema
return $data->map(function ($item) {
return [
'name' => $item->name,
'sub' => $item->sub,
'father_name' => $item->father_name,
'designation' => $item->designation,
'paid_days' => $item->paid_days, // Empty value for this column
'extra_duty' => $item->extra_duty, // Empty value for this column
'rate_of_wage' => $item->rate_of_wage, // Empty value for this column
'gross_pay' => $item->gross_pay, // Empty value for this column
'extra_wages' => $item->extra_wages, // Empty value for this column
'epf' => $item->epf, // Empty value for this column
'esic' => $item->esic, // Empty value for this column
'total_deduction' => $item->total_deduction, // Empty value for this column
'net_pay' => $item->net_pay, // Empty value for this column
'signature' => $item->signature, // Empty value for this column
];
});
}
/**
* Return the headings for the Excel file.
*
* @return array
*/
public function headings(): array
{
// Define headings in snake_case that need to be converted to Capital Case
$columns = [
'name', 'sub', 'father_name',
'designation', 'paid_days', 'extra_duty',
'rate_of_wage', 'gross_pay', 'extra_wages',
'epf', 'esic', 'total_deduction', 'net_pay', 'signature'
];
// Convert each snake_case column to Capital Case
return array_map(function ($column) {
return ucfirst(str_replace('_', ' ', $column)); // Convert to "Capital Case"
}, $columns);
}
}