Jesse Luke Orange
Jesse Luke Orange

Reputation: 1999

Comparing a date with Carbon

I am using Laravel Scout to search a model, and then I'm using a filter to get past events and upcoming events.

Here is my method:

public function search(Request $request)
{
    $search = $request->get('q');

    // Laravel Scout search() method
    $users = User::search($search)->get();
    $articles = Article::search($search)->get();
    $events = Event::search($search)->get();

    $today = Carbon::now();

    $upcomingEvents = $events->filter(function ($events) use ($today) {
        return Carbon::parse($events->startDate)->gt($today);
    });

    $pastEvents = $events->filter(function ($events) use ($today) {
        return Carbon::parse($events->startDate)->lt($today);
    });

    $userCount = count($users);
    $articleCount = count($articles);
    $eventCount = count($events);
    $upcomingEventCount = count($upcomingEvents);
    $pastEventCount = count($pastEvents);
    $templateCount = 0;

    return view('pages.search.index', compact('search', 'users', 'articles', 'upcomingEvents', 'pastEvents', 'userCount', 'articleCount', 'upcomingEventCount', 'pastEventCount', 'templateCount'));
}

I had read a tutorial here: https://scotch.io/tutorials/easier-datetime-in-laravel-and-php-with-carbon

Reading this I saw you can get today, right now, with Carbon::now().

There's also lt() for less than and gt() for greater than.

In my filter I've grabbed the start date and compared it to Carbon::now() but for some reason, it does not return what i expect.

In my database startDate is a VARCHAR but in my Event model I have specified the following:

protected $dates = [
    'startDate', 'finishDate'
];

This is my database table:

enter image description here

But in my view I get this:

enter image description here

Am I using Carbon wrongly?

Upvotes: 1

Views: 6353

Answers (2)

Foysal Nibir
Foysal Nibir

Reputation: 553

I think the problem happens with the startDate for being VARCHAR. You may convert it to a real date with a simple method below:

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

    return $date;
}

You can pass your startDate value to in and get a real date to compare with Carbon::now(). Hope this helps you.

Upvotes: 1

Matthias S
Matthias S

Reputation: 3563

I am not 100% sure if it is necessary to have the type in DB set to DATE instead of VARCHAR.

I will just assume that it works with VARCHAR, too. That would mean that by setting the $dates array in the model, your collection will automatically create a Carbon instance of the value already.

With:

return Carbon::parse($events->startDate)->gt($today);

You are parsing an already existing Carbon instance.

Try instead:

return $events->startDate->gt($today);

Upvotes: 2

Related Questions