eloquent fetch records within recent 3 hours - php

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

Related

whereBetween doesnt pick up the data from database

I am trying to get some date in between two different days:
$t = TrackingCode::where("organization_id", 10)
->whereBetween("tracking_codes.created_at", [Carbon::parse('2018-02-12 00:00:00'),
Carbon::parse('2018-02-13 23:59:59')])->get()->toArray();
I have one row where created at its 2018-02-13 13:33:41 but its not working I get an empty array/collection back;
I've also tried this so far without any success:
where("created_at", ">",Carbon::parse('2018-02-12 00:00:00'))
->orWhere("created_at","<", Carbon::parse('2018-02-13 23:59:59')
I used to chain whereDate()->whereDate() to mimick the whereBetween functionality. You might also consider moving this logic to a query scope on the model.
$query
->whereDate("tracking_codes.created_at", ">", Carbon::parse('2018-02-12 00:00:00')
->whereDate("tracking_codes.created_at", "<", Carbon::parse('2018-02-13 23:59:59')
->get()->toArray();
But maybe you can try to convert the carbon instances to a datetimestring via Carbon::parse('2018-02-12 00:00:00')->toDateTimeString().
$t = TrackingCode::where("organization_id", 10)
->whereBetween("tracking_codes.created_at", [Carbon::parse('2018-02-12 00:00:00')->toDateTimeString(),
Carbon::parse('2018-02-13 23:59:59')->toDateTimeString()])->get()->toArray();
Have you tried with created_at instead of tracking_codes.created_at?
$t = TrackingCode::where("organization_id", 10)
->whereBetween("created_at", [Carbon::parse('2018-02-12 00:00:00'),
Carbon::parse('2018-02-13 23:59:59')])->get()->toArray();
Your code should work, but I saw this difference. Perhaps can help you.
In fact, the main problem in carbon class that you use it's good with the front end or with showing the data, but when you talk to MySQL database you must be more formal, so you can use something like this:-
$firstDate = date('2018-02-12 00:00:00', time());
$lastDate = date('2018-04-05 00:00:00', time());
$t = TrackingCode::where("organization_id", 10)
->whereBetween("created_at", [$firstDate, $lastDate])->get();

Carbon::now() - only month

I couldn't find anywhere in documentation how to show current year or month with Carbon?
when i write this:
Carbon\Carbon::now('m');
it gives me the whole time stamp, but I just need the month
like
date('m');
but it must be Carbon!
How can I achieve this?
$now = Carbon::now();
echo $now->year;
echo $now->month;
echo $now->weekOfYear;
Update:
even this works since Laravel 5.5^
echo now()->month
I think you've already worked this out in a comment, but just for clarity: Carbon extends PHP's native DateTime class, so you can use any of the methods available on that, like format:
Carbon::now()->format('M');
(where M is the modifier for A short textual representation of a month, three letters)
You can use these both ways to get the current month
Carbon::now()->month;
or
Carbon::now()->format('m');
Just use this in your any blade file for print year:
{{ \Carbon\Carbon::now()->year }}
I wanted to get the current month and got to this question, to get the current month:
$now = Carbon::now();
$monthStart = $now->startOfMonth();
w/ Carbon + Laravel:
now()->format('M')
use Carbon\Carbon;
$today= Carbon::now();
echo $today->year;
echo $today->month;
echo $today->day;
echo $today->hour;
echo $today->minute;
echo $today->second;
Laravel 8
return date('m');
or
return now()->format('m');
You cant call it statically
use
$now = Carbon::now();
echo $now->month

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

How to query between two dates using Laravel and Eloquent?

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.

Categories