0

My Date format is 26-June-2020 and i run sql query

SELECT * FROM `customers` WHERE date BETWEEN '26-June-2020' AND '30-June-2020'

but its not working good its getting record from 26-june-2020 to 3-July-2020

and my laravel code is this:

$customers = Customer::whereBetween('date', array($datefrom, $dateto))->get();
2
  • 1
    Its Should be '26-06-2020' AND '30-06-2020', not '26-June-2020' AND '30-June-2020' Commented Jul 14, 2020 at 15:23
  • I have too much data in my table with this format 26-june-2020. is there any way to solve using this? Commented Jul 14, 2020 at 15:29

3 Answers 3

4

You first need to convert the dates to Carbon objects

$from = Carbon::parse($dateFrom)
    ->startOfDay()
    ->toDateTimeString();

$to = Carbon::parse($dateTo)
    ->endOfDay()
    ->toDateTimeString();

$customers = Customer::whereBetween('date', [$from, $to])->get();
Sign up to request clarification or add additional context in comments.

Comments

0

I think the problem is date format of $datefrom $dateto, I found a issue like your question How to query between two dates using Laravel and Eloquent?. Hoping it help you.

1 Comment

Welcome to Stack Overflow! This should be a comment, not an answer. If it is a duplicate question, vote to close as such and/or leave a comment once you earn enough reputation. If not, tailor the answer to this specific question.
0

If your data is in the format (e.g.) 01-June-2020 that means that your data is not correctly formatted as dates. This means you need to convert them to dates before getting a correct BETWEEN result. Not doing so will yield you a BETWEEN result comparing dates as strings, which will mean 01-June-2020 will come before 02-January-2020.

$customers = Customer::whereBetween(
    DB::raw("STR_TO_DATE(date, '%d-%M-%Y')"), 
    array($datefrom, $dateto) // These should also be correctly formatted as YYYY-MM-DD or as carbon objects
)->get();

However the major drawback of this approach is that you cannot use any indexes making any queries much slower than they could be if you permanently covert the given column to date objects and add an index.

This solution utilises STR_TO_DATE

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.