Home > Blockchain >  how to cast date in laravel model?
how to cast date in laravel model?

Time:10-17

I want to cast some field with date format. But only created_at and updated_at is formated with correctly. The invoice_date and due_date still not correct.

^ array:17 [▼
  "id" => "1"
  "vendor_id" => "12"
  "invoice_number" => "INV-1111"
  "invoice_date" => "2022-10-09 00:00:00"    <----
  "due_date" => "2022-11-08 01:52:21"     <-----
  "order_id" => "1"
  "total" => "125"
  "created_at" => "09-Oct-2022 02:10:03"    <-----
  "updated_at" => "09-Oct-2022 02:10:03"    <-----
  "invoicedetails" => array:1 [▶]
  "number_of_items" => "1"

At Model file :

protected $casts = [
    'created_at' => 'datetime:d-M-Y H:m:s',
    'updated_at' => 'datetime:d-M-Y H:m:s',
    'invoice_date' => 'date:d-M-Y',
    'duedate' => 'date:d-M-Y',
];

At migration file :

    $table->string('invoice_number');
    $table->date('invoice_date');
    $table->date('due_date');

Thank You

CodePudding user response:

The problem here is your migration creates columns with date type and in your case you want timestamp so all you need is to edit it like this

$table->timestamp('invoice_date');
$table->timestamp('due_date');

CodePudding user response:

you can cast date in laravel model as:

protected $casts = [
  'created_at' => 'datetime:Y-m-d',
];

for more visit laravel docs

for custom casting you can use accenssor feature. For laravel 9 use this:

protected function invoiceDate(): Attribute
  {
      return Attribute::make(
       get: fn ($value) => Carbon::parse($value)->format('l jS \\of F Y h:i:s A'),
   );
}

for more view official docs

  • Related