Do not return the value in the iteration, try to replace the $client->dob instead
How To Change Date Format Using Carbon
so I am looking for a way that I can transform the date format when exporting. I am using the maatwebsite/excel package. when importing the dates are changed to the following format dd-mm-yyyy hh:mm:ss which is fine for storing but when exporting I am trying to change the format to d/m/y however what I have tried doesn't seem to do anything. Im pretty sure I am missing something.
Here is the ClientsExport.php file
<?php
namespace App\Exports;
use App\Models\Tenant\Client;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ClientsExport implements FromQuery, WithHeadings
{
/**
* @return \Illuminate\Support\Query
*/
public function query()
{
$clients = Client::select(
'active',
'category',
'referral_type',
'first_name',
'middle_initial',
'last_name',
'occupation',
'dob',
'email',
'cell_phone',
'work_phone',
'has_spouse',
'spouse_first_name',
'spouse_middle_initial',
'spouse_last_name',
'spouse_occupation',
'spouse_dob',
'spouse_email',
'spouse_cell_phone',
'spouse_work_phone',
'street_address',
'city',
'state',
'postal_code',
'created_at',
'updated_at'
);
foreach($clients as $client) {
return \Carbon\Carbon::createFromFormat('d/m/y', $client->dob);
};
return $clients;
}
public function headings(): array
{
return [
'active',
'category',
'referral_type',
'first_name',
'middle_initial',
'last_name',
'occupation',
'dob',
'email',
'cell_phone',
'work_phone',
'has_spouse',
'spouse_first_name',
'spouse_middle_initial',
'spouse_last_name',
'spouse_occupation',
'spouse_dob',
'spouse_email',
'spouse_cell_phone',
'spouse_work_phone',
'street_address',
'city',
'state',
'postal_code',
'created_at',
'updated_at'
];
}
}
notice the
foreach($clients as $client) {
return \Carbon\Carbon::createFromFormat('d/m/y', $client->dob);
};
You still need to access the dob property on the $dob variable in your carbon::parse(). $dob is an object, so that would need to be $dob->dob to get the actual dob property. You also don't execute the query with first(). Do a dd($dob), what is it? A query builder instance, not your date.
$id = 9;
$client = Client::select('dob')->firstOrFail($id);
return \Carbon\Carbon::parse($client->dob)->format('d/m/y');
Please or to participate in this conversation.