How to query between two dates using Laravel and Eloquent? - php

I'm trying to create a report page that shows reports from a specific date to a specific date. Here's my current code:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', $now)->get();
What this does in plain SQL is select * from table where reservation_from = $now.
I have this query here but I don't know how to convert it to eloquent query.
SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to
How can I convert the code above to eloquent query?

The whereBetween method verifies that a column's value is between
two values.
$from = date('2018-01-01');
$to = date('2018-05-02');
Reservation::whereBetween('reservation_from', [$from, $to])->get();
In some cases you need to add date range dynamically. Based on #Anovative's comment you can do this:
Reservation::all()->filter(function($item) {
if (Carbon::now()->between($item->from, $item->to)) {
return $item;
}
});
If you would like to add more condition then you can use orWhereBetween. If you would like to exclude a date interval then you can use whereNotBetween .
Reservation::whereBetween('reservation_from', [$from1, $to1])
->orWhereBetween('reservation_to', [$from2, $to2])
->whereNotBetween('reservation_to', [$from3, $to3])
->get();
Other useful where clauses: whereIn, whereNotIn, whereNull, whereNotNull, whereDate, whereMonth, whereDay, whereYear, whereTime, whereColumn , whereExists, whereRaw.
Laravel docs about Where Clauses.

And I have created the model scope
To Know More about scopes check out the below links:
laravel.com/docs/eloquent#query-scopes
medium.com/#janaksan/using-scope-with-laravel
Code:
/**
* Scope a query to only include the last n days records
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhereDateBetween($query,$fieldName,$fromDate,$todate)
{
return $query->whereDate($fieldName,'>=',$fromDate)->whereDate($fieldName,'<=',$todate);
}
And in the controller, add the Carbon Library to top
use Carbon\Carbon;
To get the last 10 days record from now
$lastTenDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(10)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->get();
To get the last 30 days record from now
$lastThirtyDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(30)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->get();

Another option if your field is datetime instead of date (although it works for both cases):
$fromDate = "2016-10-01";
$toDate = "2016-10-31";
$reservations = Reservation::whereRaw(
"(reservation_from >= ? AND reservation_from <= ?)",
[
$fromDate ." 00:00:00",
$toDate ." 23:59:59"
]
)->get();

If you want to check if current date exist in between two dates in db:
=>here the query will get the application list if employe's application from and to date is exist in todays date.
$list= (new LeaveApplication())
->whereDate('from','<=', $today)
->whereDate('to','>=', $today)
->get();

The following should work:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
->where('reservation_from', '<=', $to)
->get();

If you need to have in when a datetime field should be like this.
return $this->getModel()->whereBetween('created_at', [$dateStart." 00:00:00",$dateEnd." 23:59:59"])->get();

Try this:
Since you are fetching based on a single column value you can simplify your query likewise:
$reservations = Reservation::whereBetween('reservation_from', array($from, $to))->get();
Retrieve based on condition: laravel docs
Hope this helped.

I followed the valuable solutions provided by other contributors and faced a minor issue no one has addressed. If the reservation_from is a datetime column then it might not produce results as expected and will miss all the records in which the date is same but time is anything above 00:00:00 time. To improve the above code a bit a small tweak is needed like so.
$from = Carbon::parse();
$to = Carbon::parse();
$from = Carbon::parse('2018-01-01')->toDateTimeString();
//Include all the results that fall in $to date as well
$to = Carbon::parse('2018-05-02')
->addHours(23)
->addMinutes(59)
->addSeconds(59)
->toDateTimeString();
//Or $to can also be like so
$to = Carbon::parse('2018-05-02')
->addHours(24)
->toDateTimeString();
Reservation::whereBetween('reservation_from', [$from, $to])->get();

I know this might be an old question but I just found myself in a situation where I had to implement this feature in a Laravel 5.7 app. Below is what worked from me.
$articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();
You will also need to use Carbon
use Carbon\Carbon;

Here's my answer is working thank you Artisan Bay i read your comment to use wheredate()
It Worked
public function filterwallet($id,$start_date,$end_date){
$fetch = DB::table('tbl_wallet_transactions')
->whereDate('date_transaction', '>=', $start_date)
->whereDate('date_transaction', '<=', $end_date)
->get();

the trick is to change it :
Reservation::whereBetween('reservation_from', [$from, $to])->get();
to
Reservation::whereBetween('reservation_from', ["$from", "$to"])->get();
because the date must be in string type in mysql

#masoud , in Laravel, you have to request the field value from form.So,
Reservation::whereBetween('reservation_from',[$request->from,$request->to])->get();
And in livewire, a slight change-
Reservation::whereBetween('reservation_from',[$this->from,$this->to])->get();

you can use DB::raw('') to make the column as date MySQL with using whereBetween function as :
Reservation::whereBetween(DB::raw('DATE(`reservation_from`)'),
[$request->from,$request->to])->get();

Another way:
use Illuminate\Support\Facades\DB;
$trans_from = date('2022-10-08');
$trans_to = date('2022-10-12');
$filter_transactions = DB::table('table_name_here')->whereBetween('created_at', [$trans_from, $trans_to])->get();

Let me add proper syntax with the exact timestamp
Before
$from = $request->from;
$to = $request->to;
Reservation::whereBetween('reservation_from', [$from, $to])->get();
After
$from = date('Y-m-d', strtotime($request->from));
$to = date('Y-m-d', strtotime($request->to));
Reservation::whereBetween('reservation_from', [$from, $to])->get();
Note: if you stored date in string form, then make sure to pass the exact format in from and to. Which will be matched with DB.

Related

How to compare created_at timestamp with Carbon date In laravel?

I have orders table , I want to get orders that have been created at this month only (delivery process happens at the same day).
I want to compare between the carbon date which refers to this current month with the created_at field of type timestamps for orders.
This is my attempt:
$month = Carbon::today();
$currentMont = $month->month;
$thisMonthOrders = Order::where('place_id',$id)->where('stage',9)->whereDate('created_at',$currentMont)->get();
dd($thisMonthOrders);
The output that it gives me is an empty array.
You'll need to use the MONTH function in MySQL, along with a whereRaw:
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereRaw('MONTH(created_at) = ?',[$currentMont])
->get();
However, you'll have issues when you have multiple years, unless you also add in a YEAR check. You might have better luck with whereBetween instead.
$start = Carbon::now()->startOfMonth();
$end = $start->copy()->endOfMonth();
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereBetween('created_at',[$start, $end])
->get();

PHP Carbon / Laravel Eloquent - Check if DateTime value is for the current day

I am working on a booking system and need to select only the records where a certain field is for today. Not today and in the future, but only today.
The query currently is:
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->where('requested_booking_time', ?????);
$advancedBookings->get();
The requested_booking_time is the field that I wish to be checked, the date stored is in this format:
2017-08-23 08:00:00
So I want to only select rows that are on the same day as the current day.
As i understand, you want that records which is created today; then just get the today's date.
$today = date("Y-m-d");
now your query is like this.
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->where('requested_booking_time', $today)->get();
You can use whereDate and format your dates with Carbon:
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->whereDate('requested_booking_time', '=' , Carbon::today()->toDateString());
$advancedBookings->get();
Or format the your date before the query with Carbon.
You should try this:
$advancedBookings = Booking::where('type', 2)
->whereNull('estimated_booking_time')
->whereDate('requested_booking_time', '=', date('Y-m-d'))
->get();

how to filter results inside where clause in laravel?

I am new to laravel, I am building a small application which alerts when event date is a week away from current date. Here is my controller code
public function index()
{
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::
where('domain_ex_date','>',date('Y-m-d'))
->get();
}
The domain_ex_date is in the format (YYYY-mm-dd) stored with the help of Carbon. The line where('domain_ex_date','>',date('Y-m-d')) gets me whole record when the domain_ex_date is away from the current date. i.e 2017-06-12 > 2016-09-15 gets the whole record. Here what i want to do is , i want to filter and get the only records which is only a week away from the current date. How do i do this ? i have tried like subweek() and subdays() but nothing helped.
I should get the record only when it satisfies this condition domain_ex_date - current date = 7
You can use strtotime():
domain_details:: where('domain_ex_date','<',date('Y-m-d',strtotime("+7 days")))
-> where('domain_ex_date','>',date('Y-m-d'))
->get();
Use Carbon!
Carbon is a build in date-extension ... Try it! :)
$week = Carbon::now()->addWeek();
$now = Carbon::now();
domain_details::where("domain_ex_date","<" $week)
->where("domain_ex_date", ">" $now)
->get()
Or you could also use the addDays($days) method!
$week = Carbon::now()->addDays(7);
I used carbon and this is what worked well for me
$week = Carbon::now()->subWeek();
$now = Carbon::now();
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::where("domain_ex_date",">", $week)
->where("domain_ex_date", "<" ,$now)
->get();

whereBetween eloquent query returns empty output

I'm trying to use 'whereBetween' eloqouent query with two given start and end dates.
$first_day_this_month = date('Y-m-01 H:s:i'); //get the first day of the current month
$yesterDay = date('Y-m-d H:s:i',strtotime("-1 days")); //get yesterday's date
$d = m_chat_history::where('employee_id',$request->other_id)
->whereNull('to_group')->where('to_employee_id',$request->id)
->whereBetween('created_at',[$yesterDay,$first_day_this_month])
->get();
I make sure I have all the required data for the query by 'var_dump' and it did gives me all the required data needed for the query but the query returns me an empty output. Any ideas, clues, suggestions, help, recommendations please? I tried to remove the 'whereBetween' and my query works like it returns me the expected output but with 'whereBetween', the return output is empty.
Make sure to use the same type and format as created_at when defining the values for whereBetween. As you're using datetime you could define edge values like (just one of many ways of doing it):
$first_day_this_month = date('Y-m-01 H:i:s');
$yesterday = date('Y-m-d H:i:s', strtotime("-1 day"));
Also make sure of the order of params (still please consider edge cases like first day of the month where $yesterday would be smaller, so you have to add some logic and be careful):
->whereBetween('created_at', [$first_day_this_month, $yesterday])
Edit: wasn't timestamp...
Try this,
but first you have to install Carbon with composer.
after doing that
use Carbon
then write the fallowing code
$yesterday = Carbon::yesterday()->toDateTimeString();
$carbon = new Carbon('first day of ' . date('F Y'));
$first_day = $carbon->toDateTimeString();
and in your query
->whereBetween('created_at', [$first_day, $yesterday])

eloquent fetch records within recent 3 hours

I need to fetch all the records which is inserted between past 3 hours to current(now). I am using laravel framework(eloquent orm).
I tried this found here
$lb = \DB::table('myTable')->whereRaw('created_at = DATE_ADD(NOW(), INTERVAL -3 HOUR');
But it return NULL. Is there any way I can do using eloquent but not Raw Query?
Any Help would be appreciated.
Laravel comes with Carbon, a nice library to handle dates, which can be used in combination with Eqlouent.
Example:
\DB::table('myTable')
->where('created_at', '>',
Carbon::now()->subHours(3)->toDateTimeString()
);
More Information
For more fun date methods, check out these docs on Carbon
http://carbon.nesbot.com/docs/#api-addsub
We can use PHP DateTime. Like this,
$date = new \DateTime();
$date->modify('-3 hours');
$formatted_date = $date->format('Y-m-d H:i:s');
$lb = \DB::table('myTable')->where('created_at', '>',$formatted_date);
In above code what we're doing is creating date string with PHP and using that in query.
add this scope to your model:
public function scopeRecent($query)
{
return $query-> whereDate('created_at ' , '=',Carbon::today())
->whereTime('created_at' , '>',Carbon::now()->subHours(3));
}
then use the scope in controller :
$posts= Post::recent()->pluck("id")->toArray();
Try This
$lb = \DB::table('myTable')->whereRaw('created_at >= DATE_SUB(NOW(), INTERVAL 3 HOUR)')
In your statement you are using = (206-07-27 11:30:00) instead >= (206-07-27 11:30:00)
try this,
include use Illuminate\Support\Facades\DB; namespace in your controller
and try this code
$results = DB::table('yourtable')->select('*')->where('created_at >= DATE_SUB(NOW(),INTERVAL 1 HOUR)')->get();
as created_at is datetime field, you can use this
\DB::table('myTable')->where('created_at', '<', Carbon::now()->subHours(3)->toDateTimeString())->get();

Categories