F
Filament10mo ago
ericmp

Eloquent orWhere question

$oneDayAgo = now()->subDay();
$twoDaysAgo = now()->subDays(2);
$threeDaysAgo = now()->subDays(3);
$oneDayAgo = now()->subDay();
$twoDaysAgo = now()->subDays(2);
$threeDaysAgo = now()->subDays(3);
is this part of an eloquent query
->where(function ($q) use ($oneDayAgo, $twoDaysAgo, $threeDaysAgo) {
$q->orWhereDate('created_at', $oneDayAgo);
$q->orWhereDate('created_at', $twoDaysAgo);
$q->orWhereDate('created_at', $threeDaysAgo);
})
->where(function ($q) use ($oneDayAgo, $twoDaysAgo, $threeDaysAgo) {
$q->orWhereDate('created_at', $oneDayAgo);
$q->orWhereDate('created_at', $twoDaysAgo);
$q->orWhereDate('created_at', $threeDaysAgo);
})
the same as this?
->where(function ($q) use ($oneDayAgo, $twoDaysAgo, $threeDaysAgo) {
$q->whereDate('created_at', $oneDayAgo);
$q->orWhereDate('created_at', $twoDaysAgo);
$q->orWhereDate('created_at', $threeDaysAgo);
})
->where(function ($q) use ($oneDayAgo, $twoDaysAgo, $threeDaysAgo) {
$q->whereDate('created_at', $oneDayAgo);
$q->orWhereDate('created_at', $twoDaysAgo);
$q->orWhereDate('created_at', $threeDaysAgo);
})
the difference is on the first orWhereDate/orWhere the objective is to retrieve the records that their creation date is 1 day ago or 2 or 3 days ago so all of them are OR but one of them must be true i've searched it and i understand they are the same, but im not confident it is. what u'd say?
5 Replies
Tally
Tally10mo ago
It's not really a Filament question.. but if you dump the query using the ->toRawSql() at the end of the query you will see the query being used... If you try them out the output will be the same
ericmp
ericmpOP10mo ago
ill try that! thanks yeah is not a filament question, hence i used non filament tag! indeed, they r the same, just tried it out thanks again! oh btw which syntax u prefer? i think 1st one, where all are orWhere, is better. cuz u clearly see they are all orWheres
Tally
Tally10mo ago
I personally like the second... same as the output

where (date(`created_at`) = '2024-05-13' or date(`created_at`) = '2024-05-12' or date(`created_at`) = '2024-05-11')

where (date(`created_at`) = '2024-05-13' or date(`created_at`) = '2024-05-12' or date(`created_at`) = '2024-05-11')
ericmp
ericmpOP10mo ago
hmm yeah but imagine somehow u switch the first line (the one that checks the one day ago) with the 2nd one then the query is different since u first do or where and then where, im gonna test if it outputs the same, not sure now yes it changes the query and the output is very different so i personally will use the orWhere in the 3 day checks, to avoid this possible not wanted changes in the query results by changing the order of the where statements
Tally
Tally10mo ago
yeah that's true... without the orWhere it is just an and date query... so if you're fiddling around the orWhere is a better option 🙂

Did you find this page helpful?