user7431257
user7431257

Reputation: 141

Laravel compare string date in database with carbon date

I have made a mistake by storing the date as VARCHAR in the database and here it looks like 02/12/2018 and I have created a variable using carbon to get the current date +14 days.

$current_date_plus_14 = Carbon::now() -> addDay(14) -> format('d/m/Y');

Problem is

I am trying to compare this date 02/12/2018 which is in the database and stores as VARCHAR to the date that I have generated using Carbon which is 09/04/2017.

Eloquent Code

$gquery = Client::where('required_date', '>=', $current_date_plus_14) -> get();

What I get

It doesn't get any results because it compare only the day in the required_date and the day in the carbon date.

While it should return value because the there is more than 1 year difference?

Upvotes: 2

Views: 2620

Answers (2)

bradforbes
bradforbes

Reputation: 696

Even if your field is a VARCHAR instead of DATETIME or DATE, you can still mark it as a date in your Eloquent model by adding the attribute name to $dates. You'll also have to change your model's $dateFormat since you have a non-Y-m-d H:i:s format.

Upvotes: 0

Irvin Chan
Irvin Chan

Reputation: 2687

Try this function that converts date as String (May work with varchar) to a real date

private function convertDateString($date)
{
    if (is_string($date)) {
        $date = Carbon::parse($date,new DateTimeZone('YOUR_DATE_TIME_ZONE'));
    }

    return $date;
}

Upvotes: 4

Related Questions