1

i am looping whole month using for loop

for ($i = 1; $i < $days; $i++) {
     $date = now()->format('Y-m-') . $i; //result '2020-08-1'
     $date = Carbon::parse($date); //parsing with carbon
     $profit = Profit::whereDate('created_at', $date->format('Y-m-d'))->first(); //<-- this not working getting null data
     $data[] = $profit;
}

but this working

$profit = Profit::whereDate('created_at', '2020-08-01')->first(); //<-- its working fine statically

what i am doing wrong help me thank you

1 Answer 1

1

This should work, I have to believe we are missing a piece of the puzzle.

That being said, you don't need to work that hard to query by date in Laravel: the query builder will accept Carbon dates no problem. So I would suggest we simplify your code to this, and see if it changes anything:

$date = Carbon::today()->startOfMonth(); // This is the first day of today's month, i.e. 2020-08-01
for($i = 0; $i < $days; $i++) {
    $profit = Profit::whereDate('created_at', $date)->first();
    $data[] = $profit;
    $date->addDay();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you but still don't know why its was not working
The new code works though? Aside from being a bit more efficient, it should amount to the same SQL query as yours... Very weird. Have you tried inspecting the SQL of your old way of doing things? i.e. Profit::whereDate('created_at', $date->format('Y-m-d'))->toSql() ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.