EN VI

How to check greater than or less than in Month, Php , Laravel Application?

2024-03-14 18:30:05
How to check greater than or less than in Month, Php , Laravel Application

My datas is Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

$currentMonth = Carbon::now()->format('M');

where('month',<,$currentMonth);

Not working

Solution:

Since the month names in your example are simple strings and hold no information about order per se, its probably best to build a list that only contains months "greater" or "lesser" than the month in question and get models with months in that list.

A possible way could be like so:

<?php

function getMonths($month, $direction)
{
    $allMonths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',];
    $key = array_search($month, $allMonths);

    if ('before' == $direction) {
        $months = array_slice($allMonths, 0, $key);
    }
    elseif ('after' == $direction) {
        $months = array_slice($allMonths, ($key + 1));
    }
    return $months;
}

$month = 'Aug';
$wantedMonths = getMonths($month, 'after');
$models = Model::whereIn('month', $wantedMonths)->get();

This function uses the whereIn query filter.

Above code is a concept, you probably need to add some more checks, like test if the month actually exists and make sure no months before Jan and none after Dec are requested, etc.

Maybe there is also some fancy Carbon or date function for this, but this seems like an easy enough solution.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login