Retrieve data between two dates in laravel - laravel-5

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();

Related

Laravel : calculate before inserting into DB

I have a form and before saving it in the DB is it possible to make a calculation?
I get a date of birth and want to make an account with the current year.
Example: 10-10-1990 and I want it to subtract from the current year.
1990 - 2021
$tabel->datenasc = $request->datenasc;
You can still do your calculations before inserting into DB
// if $request->datenasc == 10-10-1990
$current_year = date("Y");
list($day, $month, $year) = explode("-", $request->datenasc);
$year_diff = $current_year - $year;
you can now insert $year_diff in the database;
You can use setYear method from carbon library
$date = Carbon::parse("10-10-1990");
$dateWithCurrentYear = $date->setYear(now()->format('Y'));

Retrieve data between 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 06/02/2019 06/15/2019
2 06/05/2019 06/11/2019
What I want to do is, given a $date (ex: 06/08/2019 ) and get the data of the row, that the $date between started at and finished_at columns.
DB::table('table_name')->whereBetween('started_at', [$date1, $date2])
->orWhereBetween('finished_at', [$date1, $date2])->get();
$date = date('Y-m-d',strtotime($started_at));
$data = Model::where('started_at', '>', $date)->where('finished_at', '<', $date)->first();
Try this
$data = Model::where('started_at', '<', $date)->where('finished_at', '>', $date)->first();

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);

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;

Query builder where between custom date format

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);

Resources