How to change date format in laravel 9?

How to change date format in laravel 9?

Problem Description:

I got a problem

Call to a member function dateFormat() on string

This is my CollectionController.php

public function create(Request $req)
        try {
            $collection = new Collection();
            $collection->NameCollection = $req->input('NameCollection');
            $collection->Description = $req->input('Description');
            $collection->LogoImagePath = $req->input('LogoImagePath');
            $collection->WallPaperPath = $req->input('WallPaperPath');
            $collection->StartOn = $req->input('StartOn')->dateFormat();
            $collection->EndOn = $req->input('EndOn');
            $collection->CoverImagePath = $req->input('CoverImagePath');
            return $collection;
        } catch (Throwable $e) {
            return $e->getMessage();

This is my Collection.php in View

class Collection extends Model
    use HasFactory;
    protected $table = 'Collection';
    protected $primaryKey = 'IDCollection';
    protected $guarded = [];
    protected $dateFormat = 'yy-mm-dd';
    public $timestamps = false;

I want StartOn is "2022-12-06" but my function is not correct. How can I fix it ?

Solution – 1

Try to use Carbon:

$collection->StartOn = Carbon::parse($req->input('StartOn'))->format('YYYY-MM-DD');

But are you checking the format of request data ? maybe it has the right format and you don’t need to format it

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.