Query builder where between custom date format - laravel

My field date (varchar datatype) is in a custom date format it's dd-mm-yyyy.
Example : 01-01-2016
I want to get data between specific dates from a database field date. Let's say input data are stored in variables: startDate & endDate.
I tried with this query but the result are weird.
$query = DB::table('test')->whereBetween('date', array($startDate, $endDate))->get();
I think it fails because I used a custom date format.
How can this be solved?
#updated
let's say i have date like this
29-12-2015
29-12-2015
29-12-2015
30-12-2015
29-12-2015
01-01-2016
06-01-2016
i set $startDate & $endDate like this
$startDate = "01-12-2015";
$endDate = "01-01-2016";
it's even not get any result with this script
$query = DB::table('test')->whereBetween('date', array($startDate, $endDate))->get();
but if I using
$startDate = "01-12-2015";
$endDate = "31-12-2015";
i get all data...which it's wrong result because 2016 data should not in range...it's somehow like not filtered

since your date datatype is varchar you can try to use str_to_date function in mysql then before using $starDate and $endDate variable convert it's format first.
Sample code is like this.
$startDate = date("Y-m-d", strtotime("01-12-2015"));
$endDate = date("Y-m-d", strtotime("31-12-2015"));
$query = DB::table('test')->whereBetween("str_to_date(date, '%d-%m-%Y')", array($startDate, $endDate))->get();
Hope that helps.

The format shouldn't be a problem; Unless the data you POST are in different format from what the database holds. Make sure that the format for the date field in database matches the format to the ones you store in $startDate, $endDate.
Also I would solve this by taking a slightly different approach. This can become a model function, call it getDataBetweenDates(). Each time you need to query the database, to retrieve the data between a specified range of dates, you do a call to this function from the controller:
Model
public function getDataBetweenDates($startDate, $endDate) {
$range = [$startDate, $endDate];
return $this
->whereBetween('date', $range)
->get();
}
Controller
$startDate = Input::get('start_date');
$endDate = Input::get('end_date');
$model = new Model; // use your model name;
$data = $model->getDataBetweenDates($startDate, $endDate);

Related

Data is not coming in laravel 5.4 after using timestamp in query

Data is not coming when comparing current time between 2 times to fetch data in Laravel. Both times are saved in the database as timestamp and in query also I am using timestamp. Below is the code i wrote:-
$current_date = strtotime(date('d-m-Y H:i:s'));
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get();
"time_from" and "time_to" both timestamps are saved in bigint format in database. I entered timestamp using search option in direct database also still data did not come. Can someone please tell me where i am making mistake.
I think you should swap the time_from to <= and time_to to >, and try
$bookings = MachineBooking::with('userDetail')
->where('machine_id', $machine_id)
->where('time_from', '<=', $current_date) # changed
->where('time_to', '>', $current_date) # changed
->get();
You not describe what database you use. But maybe you can change to Y-m-d H:i:s format:
$current_date = strtotime(date('Y-m-d H:i:s'));
but strtotime is return int not bigint.
I hope I will help you
firstly You must cast the date in Model MachineBooking
protected $casts = ['time_from' => 'datetime:Y-m-d H:i:s',time_to =>'datetime:Y-m-d H:i:s'];
secondly
cast current date with same format of time_from and time_to
$current_date = strtotime(date('Y-m-d H:i:s'));
Please change your code with:
$current_date = strtotime(date('Y-m-d H:i:s'));
time_from and time_to are formatted date not a int . But your $current_date is int with using strtotime method
Just take strtotime method:
$current_date =date('d-m-Y H:i:s');
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get()

access data from database to compare with current date to calculate total days

I have tried to access date stored in my db table and compare it with current date so that I can get the number of days but it shows this error
DateTime::__construct(): Failed to parse time string ([{"quit_date":null},{"quit_date":null}]) at position 0 ([): Unexpected character
This is the code that use in my controller
$quit_date = Information::select('quit_date')
->where('user_id','=',\Auth::user()->id)
->get();
$date = new Carbon($quit_date);
$now = Carbon::now();
$day = $date->diffInDays($now);
but if I set the $quit_date manually with the date for example "2019-04-25 00:00:00.000000", the code works fine and shows the days different between the dates, but when I use the Information::select to read the date from database, it shows error.
use Auth; //top of controller
$checkdate = Information::
->where('user_id','=',Auth::user()->id)
->first();
$quit_date=$checkdate->quit_date;
$date = new Carbon($quit_date);
$now = Carbon::now();
$day = $date->diffInDays($now);
The issue occurs because you are using ->get() at the end of your query. That method returns a Collection not a single object. The issue is solved by using ->first() to return a single object.
The error itself is because in the line $date = new Carbon($quit_date);, Carbon cannot convert a Collection to a date.
This should work:
$quit_date = Information::select('quit_date')
->where('user_id','=', \Auth::user()->id)
->first(); //Changed this from ->get()
$date = new Carbon($quit_date);
$now = Carbon::now();
$day = $date->diffInDays($now);

Retrieve data between two dates in laravel

I am using an eloquent query to retrieve data from a table. The table columns look like this:
id started_at finished_at
1 2016-06-01 2016-06-30
2 2016-05-03 2016-05-28
What I want to do is, given a $date (ex: 2016-06-18 ) and get the data of the row, that the $date between started at and finished_at columns.
I have found whereBetween clauses in Laravel documentation, but I do not have an idea to use it correctly.
If you can use Carbon then this code will work fine for you.
$dateS = new Carbon('first day of January 2016');
$dateE = new Carbon('first day of November 2016');
$result = ModelName::whereBetween('created_at', [$dateS->format('Y-m-d')." 00:00:00", $dateE->format('Y-m-d')." 23:59:59"])->get();
Or you can check the issue by debugging query using DB::enableQueryLog(); and DB::getQueryLog(); functions like
DB::enableQueryLog();
$dateS = new Carbon('first day of January 2016');
$dateE = new Carbon('first day of November 2016');
$result = ModelName::whereBetween('created_at', [$dateS->format('Y-m-d')." 00:00:00", $dateE->format('Y-m-d')." 23:59:59"])->get();
var_dump($result, DB::getQueryLog());
Try to do something like this:
$date1 = Carbon::today()->toDateString();
$date2 = Carbon::today()->toDateString();
$myModel = MyModel::find(1);
$myModel->whereBetween('created_at', [$date1, $date2]);
$myModel->get();
Of course, you will need to change the dates.
You can use whereBetween something like this:-
ModelName::whereBetween('date',['2022-08-01','2022-10-30'])->get();

Laravel whereBetween issue , wrong records returned

I have two date variables $to and $from.
$from = '2016-06-01';
$to = '2016-06-20';
I am using whereBetween to search between the two dates.
If I select for example 1st June to 20th June it only displays records from the 1st to the 19th. How do I include the 20th in that search?
Here is an example of my where clause:
->whereBetween('CompletedDate', array($fromDate, $toDate))
The issue is the SQL server reads these dates like so...
$from = '2016-06-01 00:00:00';
$to = '2016-06-20 00:00:00';
If you want to include the latest date, you need to update these accordingly...
$from = '2016-06-01 00:00:00';
$to = '2016-06-20 23:59:59';
If you are using a datepicker, the same principle applies. Your logic would probably look something like the following...
$fromDate = new DateTime(strtotime('2016-06-01'));
$toDate = new DateTime(strtotime('2016-06-20'));
... ->whereBetween('CompletedDate', array($fromDate->format('Y-m-d 00:00:00'), $toDate->format('Y-m-d 23:59:59')));
Use Carbon
You can work better with dates using Carbon.
I came up with a little snippet for you:
<?php
public function index()
{
$from = Carbon::parse('2016-06-01')->startOfDay();
$to = Carbon::parse('2016-06-20')->endOfDay();
$users = User::whereBetween('created_at', [$from, $to])->get();
}
Carbon Documentation
Don't forget to import Carbon:
use Carbon\Carbon;

Laravel Date comparison not working in Eloquent query

I do not understand why but following query return null resultset.
due_date is Carbon date and $now=Carbon:today();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>=',$now)
->where('due_date','<',$now->addMonth())
->get();
Also when I use whereBetween it doesn't work.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$now, $now->addMonth()])
->get();
But when I just to greater than or lesser than it works
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>',$now->addWeek())
->get();
What am I missing here?
The problem here is that you are using the same instance for both range limits. When you call addMonth you add the month to the instance stored in $now. The two examples below illustrate the issue:
1. Using and modifying the same variable in two separate statements works as you'd expect:
$now = Carbon::now();
dump($now); // prints 2015-12-12 14:50:00.000000
dump($now->addMonth); // prints 2016-01-12 14:50:00.000000
2. Using the same variable and modifying it in the same statement that passes the values to a method, will work differently, because it will be evaluated before being passed to the method. Meaning that both parameters will be equal because they both contain the same instance from the $now variable, which after getting evaluated will contain the DateTime of one month from now.
$now = Carbon::now();
// Calling `addMonth` will change the value stored in `$now`
dump($now, $now->addMonth());
// The above statement prints two identical DateTime values a month from now:
// 2016-01-12 14:50:00.000000 and 2016-01-12 14:50:00.000000
This means that your current code was checking if the entries were due only exactly one month from now.
To fix it you need to use two instances in two separate variables:
$from = Carbon::now();
$to = Carbon::now()->addMonth();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$from, $to])
->get();
It looks like it is because I used '$now' in the query.
Like is said before the query I did $now=Carbon::today(); and use $now in the query.
But then I got rid of that and changed the query to use Carbon::today() it worked.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[Carbon::today(), Carbon::today()->addMonth())
->get();
It is weird.
Thanks,
K

Resources