Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GTHell's avatar

How to efficiently check for holiday in Laravel?

I just realize that I don't know how to implement a logic that involve checking for holiday. I don't think it's good to query the holiday table and then loop through collection with if statement to check if the the current transaction is in the holiday day. If it's the only option then I have nothing against it but I don't think so.

I prefer something like the array manipulation of Javascript indexOf()

0 likes
4 replies
lostdreamer_nl's avatar

if you're only doing 1 check, I suggest something like a query : Holiday::where('start', '<=', $now)->where('end', '>=', $now)->exists();

to check if there is a holiday around 'now'.

If you have a list of holidays, and need to check a list of transactions against that holidays list:

// 1 query here
$holidays = Holiday::get();
foreach($transactions as $transaction) {
    // no queries here as they are already inside your collection
    $isHoliday = $holidays->where('start', '<=', $now)->where('end', '>=', $now)->exists();
    dd($transaction, $isHoliday);
}
samo's avatar

Hi @gthell,

what exactly are you trying to do?

if you simply want a 'isOnHoliday' method on your transaction model you could go the way to fetch all holidays where the transaction->created_at is inside the holiday->date_from and holiday->date_to...

if i dont misunderstood you, your could do something like this:

// Transaction.php Model

public function isOnHolidays()
{
    return Holidays::where('date_from', '<=', $this->created_at)
        ->where('date_to', '>=', $this->created_at)
        ->exists();
}

On the other side you could make a sql join.

lostdreamer_nl's avatar

@gthell

start and end should be 2 fields on your Holiday table, a holiday could start on 2018-12-25 and end on 2018-12-26

if you only set days as a holiday (and have a field called day in the holiday table) you could do the check like this:

$holidays = Holiday::get();
foreach($transactions as $transaction) {
    // no queries here as they are already inside your collection
    $isHoliday = $holidays->where('date', substr($this->created_at, 0, 10))->exists();
    dd($transaction, $isHoliday);
}

Or add an extra attribute to the Transaction model:

public function getIsOnHolidayAttribute() 
{
    return Holidays::where('date', substr($this->created_at, 0, 10))->exists();
}

$transaction = Transaction::find(5);
dd($transaction->toArray(), $transaction->is_on_holiday);

Please or to participate in this conversation.