Query using eloquent whereMonth where date is string - laravel

In one of the tables a column with type of varchar contains a date with the following format day-month-year. I would like to run a query using eloquent on that table with whereYear and whereMonth, but I get an error since the column booking_date is not of type Date.
The query I am trying to run is
MyTable::whereYear('booking_date', '=', $year)
->whereMonth('booking_date', '=', $month)
->get();
And getting the following error
"SQLSTATE[42883]: Undefined function: 7 ERROR: function pg_catalog.date_part(unknown, character varying) does not exist\nLINE 1: ...\" = $1 and \"said_table\".\"deleted_at\" is null) and extract(ye...\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.
Is there a way to cast the string value to a date before querying it, maybe with using raw expressions? If yes, any hints would be great.

If this field is going to be a date on the particular model all the time (and with a name like 'booking_date', it might well be), it is even easier than having to deal with it on every query. You can cast it within the dates field on the model itself:
protected $dates = [
'booking_date',
];
By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, and the above will do the same for booking_date. No further casting required. From Laravel docs on date mutators

You may easily achieve that thanks to Carbon library which is included within Laravel:
use Carbon\Carbon;
$targetDate = Carbon::now()->year($year)->month($month);
MyTable::whereYear('booking_date', '=', $targetDate)
->whereMonth('booking_date', '=', $targetDate)
->get();

Related

Laravel 8: why is sorting by date in eloquent is wrong, using Carbon

Possible duplicates:
Laravel: How to order date, change the date format and group by the date?
Laravel Carbon format wrong date
I created a line chart using chartjs, the chart and data fetching is working fine. However the order of the dates is wrong. It starts off with Aug 2022 instead of Jan 2022.
When I use the orderBy(), it shows orderBy() doesn't exists error.
When I use createFromFormat() of Carbon, it shows missing data error.
Why? I parsed the date with Carbon and the column type is datetime, shouldn't it be working?
This is my laravel collection:
$data = TrafficViolation::select('id', 'violationDateTime')
->get()
->sortBy('violationDateTime')
->groupBy(function($data) {
return Carbon::parse($data['violationDateTime'])->format('M, Y');
});
The orderBy() is a Query Builder method. Once you call get(), you get a Collection instance.
To order the records in your DB you need to call orderBy() first, and than get():
UPDATE:
I have included the records count, and date format. You still need to order the records by the violationDateTime column
$data = User::selectRaw('COUNT(*) as violation_count, DATE_FORMAT(violationDateTime, \'%M, %Y\') as formatedDate')
->groupBy('formatedDate')
->orderBy('violationDateTime')
->get();
if your get a Syntax error or access violation: 1055 you need to change the stritc mode in mysql to false in /config/database.php change ['connections' => ['mysql' => ['strict' => false]]]

Laravel eloquent compare datetime with query builder

I'd like to compare datetime values (with date AND time). First I tried this, but it does not work, as it only compares the date, not the time:
$events = $events->whereDate('end', '>=', $input['after']);
I thought that a simple where would help, but it does not:
$events = $events->where('end', '>=', $input['after']);
The reason for that is, that my input value is 2022-10-10T00:00:00 and the database read gives 2022-10-10 00:00:00 (the T in the middle was added in the input).
I'd like to stick to the isoformat (using the T), however inside the database that format gets casted to a value without T it seems. The reason for that might be the cast in the model: 'end' => 'datetime',
What would be the best way to solve this issue and compare datetime objects (and how)?
Change the model cast
Cast the input
What would be the best way to solve this issue and compare datetime objects
The best way is still to convert the input with the data type format of the date and time column
You can use : $dateConvert = date('Y-m-d H:i:s', strtotime($input['after']));
But I suggest you use carbon library :
$dateConvert = \Carbon\Carbon::parse($input['after'])->format('Y-m-d H:i:s');
And :
$events = $events->where('end', '>=', $dateConvert );

Laravel eloquent query with nested whereDate

I currently have a table called operators
The columns are:
id, user_id, item_clicked, created_at, updated_at
I can confirm on one of these it has today's update_at
2019-08-05 showing as today.
This is a relational table.
operators belongs to users.
I'm attempting to get operators of users whereDate is today.
My code is:
$ordersClicked = User::with('operators')
->whereDate('updated_at', \Carbon\Carbon::today())
->get();
This returns an empty array.
Testing this works so I know the data I need is there.
$ordersClicked = User::with('operators')
->get();
$operator = Operator::whereDate('updated_at', \Carbon\Carbon::today())->get();
Any idea what I'm doing wrong?
According to the docs https://carbon.nesbot.com/docs/ Carbon::today() returns Y-m-d H:i:s, if used like you are doing in a where clause and the database stores the value in Y-m-d format.
Why don't you try this:
$ordersClicked = User::with('operators')
->whereDate('updated_at', \Carbon\Carbon::today()->format('Y-m-d'))
->get();
if that doesn't work; then it is possible the eloquent is applying the where clause on updated_at on the User table, instead of Operator. Did you mean to do something like this:
$ordersClicked = User::with(['operators' => function($query) {
$query->where('updated_at', \Carbon\Carbon::today()->format('Y-m-d'))
}])->get();
i.e. filter on the eager loaded collection? if this is what you intended, what will happen is it will return all users and only some operators that has the updated_at matching the criteria will have values, where others will be null.
Wouldn't it be better to reverse the query? i.e. make sure Operator has a belongsTo relationship on User model and query the data like this:
$operator = Operator::whereDate('updated_at', \Carbon\Carbon::today())
->with('user')
->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)

How to use whereBetween for dates in Laravel

I am trying to get the number of new users for each week using the created_at column. I am trying to use the whereBetweensyntax but it always return 0 even when it is suppose to return otherwise.
{{ DB::table('users')
->whereBetween('created_at', array(date("Y/m/d h:i:s", strtotime('sunday last week')), date("Y/m/d h:i:s", strtotime('saturday this week'))))->count(); }}
Any suggestions?
The query itself should work as written, though you might want to verify that created_at is a column of either timestamp, date, or datetime type. When you created the users table, did you use a migration to create your users table, and if so, did you specify $table->timestamps();? Or did you manually define the created_at column, and perhaps set it to a string?
A couple other (unrelated) suggestions:
• It appears that you're running this query in a view, echoing the count using blade. This logic would be better handled elsewhere, perhaps in your User model, and the result passed to the view by the controller.
• You can simplify your query using PHPs DateTime object, replacing your date(...strtotime...) with date_create(...):
$usersThisWeek = User::whereBetween(
'created_at', array(
date_create('sunday last week'),
date_create('saturday this week')
))->count();

Resources