Comparing dates in a query using Eloquent - laravel

How can I create a query like
WHERE DATE(created_date) = '2014-05-26'
in Laravel?
I got this
->where('created_date', Input::get('date'))
but it doesn't work because created_date is datetime

By using the DateTime class maybe :
->where('created_date', new DateTime(Input::get('date')))
It should work!

Try this
where('created_date', '>', $date->startOfDay()->toDateTimeString())
->where('created_date', '<', $date->endOfDay()->toDateTimeString())
->get();
and take a look at this:
Laravel eloquent get model on date

You have to convert you string representation of the date into a Carbon instance.
$date = Carbon\Carbon::parse(Input::get('date'));
$results = Model::where('created_date', $date);
Happy coding!

I think the best option, and most logical one, is the following:
$results = Model::whereDate('created_date', Input::get('date'));
Use of Carbon is optional here.

Related

Could someone help me build the elequent query laravel

I am on laravel, I am developing a library. I would like to display a list of books with a publication date of less than 3 months. Could someone help me build the elequent query. I tried with the DB class but it doesn't work.
$today = date('Y-m-d');
$books = DB::select("SELECT * from books where(DATEDIFF($today, 'publication_date') <=90)");
You can benefit from laravel query builder and pass now()->subDays(90) as the point that the date must be greater than.
DB::table('books')
->whereDate('publication_date', '>', now()->subDays(90))
->get();
The carbon package that comes with Laravel is quite handy for these types of thing.
What you could do is the following:
$books = Book::where('published_date', '<=', now()->addMonths(3))->get();

Laravel Eloquent compare dates by specific format

I am having a little trouble comparing dates in Laravel, where the date is a specific format.
The field in the database has the date like this d-m-Y(20-04-2018) and I am trying to get a result where this date is greater than the date now using this.
$check= Usersubstitutions::where([
['user_id', '=', $request->user],
['date_to', '>=', date("d-m-Y")]
])->first();
And it never works. I var dumped to see what compares, using a foreach and it says that 20-05-2018 is NOT greater than 04-04-2018.
Convert your column to a date format, such as DATE, and then it will work as intended.
Since your field is a varchar try to cast it first to DATE then compare it with date('d-m-Y') like :
$check= Usersubstitutions::where('user_id', $request->user)
->where(DB::raw("DATE(date_to) >= '".date('d-m-Y')."'"))
->first();
NOTE : It will be better to convert the field type in your database to 'DATE'.
On Laravel 4+ you may use
->whereDate('date_to', '>=', date("d-m-Y")
For more examples, see first message of #3946 and this Laravel Daily article.
but you may also use the ->where() as its more convenient.
Try this:
$dayAfter = (new date()->modify('+1 day')->format('d-m-Y');
->where('date_to', '>=', $dayAfter)
Hope it helps. if not view this qn for further explanations
You seem to be storing a DATE in a varchar field. That's not a good idea. You need to either re-create the table and store date_to as a date using the standard SQL DATE format (and use the format Y-m-d when inserting) or cast the column to a date when selecting:
$check= Usersubstitutions::where([
['user_id', '=', $request->user],
[\DB::raw("STR_TO_DATE(date_to,'%d-%m-%Y')") ', '>=', date("Y-m-d")]
])->first();
Note this will make any indexes useless and will make the query run very very (very) slowly.
Note: STR_TO_TIME is MySQL only but there are equivalents in other DBMSs e.g. in SQL Server it seems to be CONVERT(DATE, date_to, 105)

Laravel 5.4: How do I get records from just this week?

To get all records of the current day, I did
$dt = Carbon::now();
$dataToday = Data::whereDay('created_at', $dt->day)->get();
To get records from this week, I tried the following but without success.
$dataThisWeek = Data::where('created_at', $dt->weekOfYear);
$dataThisWeek = Data::where('created_at', $dt->weekOfMonth);
$dataThisWeek = Data::whereWeek('created_at', $dt->week);
How do we approach this with Eloquent and Carbon (preferably) or a native MYSQL function?
Try this:
Data::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();
To set the week start/end:
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
You can also try
$dataThisWeek = Data::where(\DB::raw("WEEKOFYEAR(created_at)"), $dt->weekOfYear)->get();
For some reason using Laravel 7.4^ the accepted solution above is not working on my end. No data is shown, to fix it I added a format like this:
$now = Carbon::now();
Data::whereBetween("created_at", [
$now->startOfWeek()->format('Y-m-d'), //This will return date in format like this: 2022-01-10
$now->endOfWeek()->format('Y-m-d')
])->get();
To complete #user320487 answer:
To avoid conflict between different third-party libraries, static setters should not be used. Use $weekEndsAt optional parameter instead when using endOfWeek method.
Data::whereBetween('created_at', [Carbon::now()->startOfWeek(Carbon::SUNDAY), Carbon::now()->endOfWeek(Carbon::SATURDAY)])->get();
You can also use the 'first_day_of_week' locale setting to change the start of week according to current locale selected and implicitly the end of week.

Group By Eloquent ORM

I was searching for making a GROUP BY name Eloquent ORM docs but I haven't find anything, neither on google.
Does anyone know if it's possible ? or should I use query builder ?
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
Laravel 5
WARNING: As #Usama stated in comments section, this groups by AFTER fetching data from the database. The grouping is not done by the database server.
I wouldn't recommend this solution for large data set.
This is working for me (i use laravel 5.6).
$collection = MyModel::all()->groupBy('column');
If you want to convert the collection to plain php array, you can use toArray()
$array = MyModel::all()->groupBy('column')->toArray();
try: ->unique('column')
example:
$users = User::get()->unique('column');

Laravel/Eloquent and comparing dates

I want to return all of the rows in my database table that are a day or less old. I'm using Laravel 4. This is what I tried:
$date = date('Y-m-d H:i:s');
return MainContact::where(DATEDIFF('timestamp', $date), '<=', 1)->get();
This doesn't work. I read the documentation and it doesn't seem like you can pass Laravel MySQL functions. timestamp is a datetime field. How can I compare these dates in Laravel 4?
The answer that user1977808 gave you is not good because MySQL can't use an index on the timestamp column, since it has to compute an output of the DATE_SUB function for every row. Avoid such queries, they have to process the entire table every time!
How about something like this:
return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();
I put the >= in there because you said "a day or less old", so they must have timestamp that is later than yesterday.
Alternatively,
You can use Carbon API that bundle with Laravel.
ModelName::where( 'timestamp', '>=', Carbon::now() )->get();
Reference: http://laravel.com/docs/5.1/eloquent-mutators
You could also use whereDate(), whereDay(), whereMonth() and whereYear(). In this case, whereDate() could be used as such, with Carbon's easy date functions:
return MainContact::whereDate('dateField', '<', Carbon::now()->subDay())->get();
return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();
You can also do a raw query by using:
$results = DB::query( 'query' );
You only don't the the model object back in the results var

Resources