I'm trying to fetch relational data from a model where the date column is higher or equal to the current time.
The date column is formated as this: Y-m-d H:i:s
What I'm trying to do is to grab all rows where the Y-m-d H:i:s is in the future.
Example: lets assume the date is 2017-06-01 and the time is 09:00:00
Then i would like got all rows where the date is in the future, and the time is in the future.
Currently my code looks like this, and it's almost working but it doesn't grab the rows where the date is the current day.
public function customerCardFollowups() {
return $this -> hasMany('App\CustomerCardFollowup', 'user_id') -> whereDate('date', '>', Carbon::now('Europe/Stockholm')) -> orderBy('date', 'asc') -> take(20);
}
What am I doing wrong?
Sounds like you need to use >=, for example:
->whereDate('date', '>=', Carbon::now('Europe/Stockholm'))
Here you can use this:
->where('date', '>=', date('Y-m-d'))
Using whereDate will compare the date only and ignore the time. So your solution will give the records that are at least dating one day later and the records that are in the same day but with later hours will not be included.
If you use >= as suggested in other answers, you will get records starting from the current date and those ones who are even before the determined hour.
One solution for this is comparing using MySQL functions in whereRaw. In your code the condition for the date will be like this:
-> whereRaw("date > STR_TO_DATE(?, '%Y-%m-%d %H:%i:%s')" , Carbon::now('Europe/Stockholm')->format('Y-m-d H:i'));
In the code, I changed the format of Carbon date to match a specific format where you can use whatever format you want and put the same format in the STR_TO_DATE function.
For Laravel's TestCases:
$this->assertDatabaseHas('my_table', [
'name' => $name,
[ 'updated_at', '>=', $updatedAt ] // $updatedAt is a Carbon object
]);
Related
In DB Col Name('publish') varchar format d/m/Y for Example 30/1/2020
when try to get dates less than 30/1/2020 get any date less than days
for example
->where('publish','<','30/01/2020')
29/2/2020 less than 30/1/2020 so i get any date under 30 by day not month or year
on your Eloquent model define an accessor to retrive publish as carbon object
public function getPublishAttribute($date)
{
return Carbon::parse($date)->format('d/m/Y');
}
now on your controller compare both date as below
->where('publish','<',Carbon::parse('30/01/2020'))
hope it helps!
You can use DB::raw and str_to_date for the same:
->where(DB::raw('str_to_date(publish, "%d/%m/%Y")'),'<','30/01/2020' )
str_to_date will convert your varchar field to datetime field.
MySQL -> Date and Time Functions-> STR_TO_DATE
I am trying to make a notification for the agents in my CRM.
I store the date and time they pick in my database and compare it to the current data and time.
I have tried this:
$notification = Main::select('id') -> whereRaw('Date(notification) = CurDate()') -> where('user_id', '=', $userid) -> get();
it works perfectly but compare only the current date with the saved date.
What I am looking for is to compare the current date and time with the stored date and time. If that time and date match or passed then do anything.
I don't want to use Carbon because I don't know how to use it.
You can try something like this instead:
$notification = Main::select('id')
->where("notification", "<=", date("Y-m-d H:i:s"))
->get();
We have an application in Laravel 5.2. In our database, published_at stores date in timestamp with carbon instance in UTC, just as created_at and updated_at.
Every post is supposed to be published at midnight in every timezone. We saved our dates data in UTC format, like
'published_at' => '2016-04-12 00:00:00'
What we want to do is like;
if a person in US views it, then he/she sees that post after his/her midnight time. If a person in China views it, then he/she sees that post after his/her midnight time. How can we achieve this?
This is what we are doing at the moment. But, we think it's not gonna work.
public function all($limit, array $data = [])
{
$posts = $this->post->with('categories')
->where(
'published_at', Carbon::now()->setTimezone($data['user_timezone'])
->format('Y-m-d 00:00:00')
)
->orderBy('published_at', 'ASC')
->paginate($limit);
}
This is the first time we are working in timezones and we have no idea. Any help would be greatly appreciated. Thank you.
It sounds like you're trying to do a "sequential timezone publish", where over the course of 24 hours, it's midnight somewhere.
Assuming you've grabbed the timezone from input somewhere (in $data?), you can use the standard Eloquent / Laravel Query Builder verbiage to construct the query you require:
https://laravel.com/api/master/Illuminate/Database/Query/Builder.html
public function all($limit, array $data = [])
{
$posts = $this->post->with('categories')
->where(
'published_at',
'<',
Carbon::now($data['user_timezone'])
->format('Y-m-d H:i:s')
)
->orderBy('published_at', 'ASC')
->paginate($limit);
}
That way as soon as "midnight" has occurred in the timezone being passed through, the "published_at" will have a value of "less than" the current timestamp, including it in the results.
I want to get all the rows from a table through an expression:
table.date <= 2014-07-10
But if the column contains a datetime let's say:
2014-07-10 12:00:00
But if I do:
where('date', '<=', $date)
it won't get the row.
I guess this is because $date = 2014-07-10 which makes MySQL assume that it is 2014-07-10 00:00:00.
In regular MySQL I would just do
where DATE(date) <= $date
What would be the equivalent using Laravel's Eloquent?
Laravel 4+ offers you these methods: whereDay(), whereMonth(), whereYear() (#3946) and whereDate() (#6879).
They do the SQL DATE() work for you, and manage the differences of SQLite.
Your result can be achieved as so:
->whereDate('date', '<=', '2014-07-10')
For more examples, see first message of #3946 and this Laravel Daily article.
Update: Though the above method is convenient, as noted by Arth it is inefficient on large datasets, because the DATE() SQL function has to be applied on each record, thus discarding the possible index.
Here are some ways to make the comparison (but please read notes below):
->where('date', '<=', '2014-07-10 23:59:59')
->where('date', '<', '2014-07-11')
// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');
->where('date', '<', $dayAfter)
Notes:
23:59:59 is okay (for now) because of the 1-second precision, but have a look at this article: 23:59:59 is not the end of the day. No, really!
Keep in mind the "zero date" case ("0000-00-00 00:00:00"). Though, these "zero dates" should be avoided, they are source of so many problems. Better make the field nullable if needed.
Have you considered using:
where('date', '<', '2014-08-11')
You should avoid using the DATE() function on indexed columns in MySQL, as this prevents the engine from using the index.
UPDATE
As there seems to be some disagreement about the importance of DATE() and indexes, I have created a fiddle that demonstrates the difference, see POSSIBLE KEYS.
You can get the all record of the date '2016-07-14' or before '2016-07-14' by choosing one syntax from follows:
->whereDate('date','=','2014-07-10')
->whereDate('date', '<=', '2014-07-10')
Or use the another code for dynamic date
whereDate('date',$date)
You can use this
whereDate('date', '=', $date)
If you give whereDate then compare only date from datetime field.
use Carbon\Carbon;
public function scopePublished($query)
{
$now = Carbon::now();
$date = Carbon::parse($now)->toDateString();
$time = Carbon::parse($now)->toTimeString();
return $query->whereDate('published_at', '<', $date)
->orWhere(function($query) use ($date, $time) {
$query->whereDate('published_at', '=', $date)
->whereTime('published_at', '<=', $time);
});
}
Here is my logic:
if you are comparing date then your method should be whereDate and if your comparing complete datetime then your method will be only where:
$calendar_alert = DB::table('calendar_alerts')->whereDate('when', '=', now()->format('Y-m-d'))->where('when', '>', now()->format('H:i:s'))->get();
If you're still wondering how to solve it.
I use
protected $dates = ['created_at', 'updated_at', 'aired'];
In my model and in my where i do
where('aired', '>=', time());
So just use the unix to compare in where.
In views on the other hand you have to use the date object.
Facing the same issue, I suggest to read this article : https://dev.to/nicolus/how-to-properly-retrieve-laravel-models-between-two-dates-1bek
Note that the statement :
The issue here is that our created_at column is usually a Datetime, so it's not a simple date but it also has a time. Which means that in practice any post created on the 30th won't be retrieved because their creation date will always be greater than 2021-06-30 (which SQL will assume means '2021-06-30 00:00:00').
... from the article isn't completly true because on my side I tested a direct comparison between a mysql "date" typed field and a string formatted like "2022-10-18", and the issue was the same, the "<=" didn't work right.
I'm using Laravel Framework.
I want all of the rows for this day. This is what I tried:
DB::table('users')->where('created_at', '>=', date('Y-m-d H:i:s'))
(field created_at represented in database in format: Y-m-d H:i:s).
Hmmm...there was a good answer to this question which seems to have now disappeared.*
It was something like this:
User::where('created_at', '>=', new DateTime('today'))
Note: if you're putting this code in a file with a namespace, or might use a namespace in the future, you should prefix the DateTime class with a backslash: new \DateTime('today').
*
https://stackoverflow.com/questions/15052679/laravel-framework-how-to-get-today-queries
date('Y-m-d H:i:s') returns date of now.
If you want results from start of the day you can replace it with date('Y-m-d').' 00:00:00'.
If you want results from last 24 hours you can replace it with date('Y-m-d H:i:s',time()-86400) (86400 = 24*60*60)
For those who only need to compare a date without time, Lavarel provided a handy function whereDate:
User::whereDate('created_at', '>=', date('Y-m-d'));
http://laraveldaily.com/eloquent-date-filtering-wheredate-and-other-methods/
I know that topic is old but may someone try to find a solution from search engines.
You can use:
User::whereDate('created_at', '=', Carbon::today()->toDateString());
You can visit this link if you want to know more about date comparison in Laravel using where.
Eloquent date filtering: whereDate() and other methods
Simply:
DB::table('users')->where('created_at', '>=', date('Y-m-d'). ' 00:00:00')
When getting all rows for this day(the time should be 00:00:00), so make sure to set the date condition to current date plus 00:00:00 i.e.
date('Y-m-d'). ' 00:00:00'
Use whereDate
$users = DB::table('users')
->whereDate('created_at', '2016-12-31')
->get();
other functions you may use are: whereDate / whereMonth / whereDay / whereYear / whereTime