Chonchol Mahmud
Chonchol Mahmud

Reputation: 2735

Get wrong formatted date in Laravel API

I am making a API request but when i retrieve created_at then i get 2019-10-09T11:07:08.000000Z but in database it is 2019-10-09 11:07:08. How can i solve this issue? I don't want to use date formatting because i already have proper date format in my database. I just want what i have in database. Look at my database: https://prnt.sc/piljms

API Controller:

 public function singleGallery($id)
    {
        $gallery = Gallery::findOrFail($id);
        return new GalleryResource($gallery);
    }

Gallery Resource:

    return [
        'gallery_id' => $this->id,
        'created_date' => $this->created_at,
        'modified_date' => $this->updated_at
    ]

Upvotes: 0

Views: 1990

Answers (3)

Chintan Hingrajia
Chintan Hingrajia

Reputation: 329

<?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use DateTimeInterface;
    
    class Notification extends Model
    {
        use HasFactory;
        
        protected $fillable = [
            'id',
            'created_at',
            'updated_at',
        ];
        
        protected function serializeDate(DateTimeInterface $date)
        {
            return $date->format('Y-m-d H:i:s');
        }
    }
    ?>

Upvotes: 0

fox91
fox91

Reputation: 362

Go with this:

return [
    'gallery_id' => $this->id,
    'created_date' => $this->created_at->format('Y-m-d H:i:s'),
    'modified_date' => $this->updated_at->format('Y-m-d H:i:s'),
]

Upvotes: 0

Avnish Tiwary
Avnish Tiwary

Reputation: 2276

Using php's date and strtotime function you can format date as per your choice.

'created_date' => date('Y-m-d', strtotime($this->created_at))

I have formatted created_at in Year/month/date but you can do different formatting like d/m/Y for day/month/Year

If you would like to go Laravel way then you have to use Carbon library.

Upvotes: 1

Related Questions