I need to grab this month data for user in database so I write:
dd($user->products->where('paid',1)->where('created_at','>=', Carbon::now()->startOfMonth()->toDateString())->all());
and I got 0 results...
When I try Carbon::now()->subMonth() its works good but return me last 30 days ...
How I can solve this? How to get only this month data ?
->toDateString() is causing the query to look for a string value, and not a date. There's two ways to solve this:
(...)->where('created_at', '>=', Carbon::now()->startOfMonth())
// OR
(...)->whereDate('created_at', '>=', Carbon::now()->startOfMonth()->toDateString())
If you just use a Carbon variable, Laravel knows to check for date logic. Alternatively, if you're using a string, you can override the where logic to treat it as a date by using ->whereDate()
Related
I'm trying to query based on two databases and columns.
$model->where('response_time', '<=', Carbon::now()->subMinutes(\DB::raw('anotherTable.created_at'))->diffInMinutes(Carbon::now()))
response_time contains an integer of minutes, ie: 15
If the anotherTable.created_at - response_time (ie, sub 15 mins) is less than the current time, return the row.
I've tried the above but I'm having no luck and no idea how to debug my query. Any help appreciated.
Example query that should pass and return its row (1 minute over):
response_time 15
anotherTable.created_at 21-03-2022 13:40:00
Current time: 21-03-2022 13:56:00
Why Carbon is not working
Carbon is unable to retrieve the value from the database during query generation on the PHP side ($model->where()). Carbon will instead execute immediately on the string value of 'anotherTable.created_at' prior to issuing the query to the database. The equivalent of:
$offset = Carbon::now()
->subMinutes('anotherTable.created_at')
->diffInMinutes(Carbon::now()); // 0
$model->where('response_time', '<=', $offset); // WHERE responst_time <= 0
Carbon Process Breakdown
Carbon\Traits\Date::__call() is used to parse the action and units from the method name as sub and minutes.
The process conditionally calls Carbon\Traits\Units::subUnit('minute', 'anotherTable.created_at') [sic] which calls Carbon\Traits\Units::addUnit($unit, -$value, $overflow) [sic].
The -$value is ultimately processed by PHP as -'anotherTable.created_at' resulting in 0 as if you called Carbon::now()->subMinutes(0).
The issue would have been pointed out if Carbon would throw a TypeError exception when provided a string for the $value argument, as opposed to the expected int. However, the $value argument of Carbon\Traits\Units::subUnit($unit, $value) is not type-hinted.
MySQL Resolution
Instead of using Carbon, use the MySQL TIMESTAMPDIFF() function to produce the difference in minutes between anotherTable.created_at and NOW() in the query.
db<>fiddle Example
Provided anotherTable is being added with a JOIN in the query.
$model->where(
'response_time', '<=', DB::raw('TIMESTAMPDIFF(MINUTE, anotherTable.created_at, NOW())')
);
Give this a try :)
$model->where('response_time', '<=', Carbon::now()
->diffInMinutes(\DB::raw('anotherTable.created_at')));
You cannot rely on the table values being used in a carbon function.
Instead, you have to do your caulcations on the database.
The code below should work in theory, though I have not tested it out.
All culcations that require database data, are done on the database.
Carbon is only used to pass the condition value up to it.
$model->where(
DB::raw('DATE_SUB(anotherTable.created_at, INTERVAL response_time MINUTE)'), '<=', Carbon::now()
);
i hope this will help you
Carbon::parse('21-03-2022 13:40:00')->diffInMinutes(new DateTime)
Or
Carbon::parse('21-03-2022 13:40:00')->diffInMinutes(Carbon::now())
in your case use this:
Carbon::parse(DB::raw('anotherTable.created_at'))->diffInMinutes(Carbon::now())
I am using laravel 8 and I want to get ids between two dates form created_at column which is timestamp format I use the following code
$ids=Visit::select('id')->whereBetween('created_at',[$request->input('from_date'),$request->input('to_date')])->get();
return response($ids);
but I get an empty result
I tired to convert the inputs to time using the strtotime() function but also I get the same empty result
$ids=Visit::select('id')->whereBetween('created_at',[strtotime($request->input('from_date')),strtotime($request->input('to_date'))])->get();
return response($ids);
the input type in view page is date
could you please help with the correct syntax
You can format using carbon
$fromDate=\Carbon\Carbon::createFromFormat('Y-m-d',$request->input('from_date'));
$toDate=\Carbon\Carbon::createFromFormat('Y-m-d',$request->input('to_date'));
$ids=Visit::select('id')->whereBetween('created_at',[$fromDate,$toDate])->get();
return response($ids);
So I have this query:
Report::whereDate('date', '=', Carbon::now()->format('Y-m-d H:i'))->get();
Dates are stored like this for example:
2017-01-08 10:00:00
But I never get any results, does this have to do something with the seconds? If so, how can I avoid this and get my results? Using a mutator perhaps to ignore seconds?
PS. I want to get the results from the specified time, because I am using it for a scheduled task (command). E-mails should be sent at specified times, and the times vary :)
You can try with WhereRaw
$format = Carbon::now()->format('Y-m-d H:i');
Report::whereRaw("date_format(date, '%Y-%m-%d %H:%i ') = '$format'")
I figured it out, I didn't want to use a boolean in my database to check wether or not an e-mail has been sent for the specific report, because they are daily reports. But I will another cron job to reset these booleans at the end of the day.
Add date to $dates property in the Report model:
protected $dates = ['date'];
You said you want to check the time, so just do this:
Report::where('date', Carbon::now())->get();
I guess I've mis understood the question.
The convenient way to match date time is by using Carbon.
In your model add the following line.
protected dates = ['date'];
By doing that your dates will be saved as Carbon instance.
Now you can do
Report::whereDate('date', Carbon::now())->get();
I have stored the date as a string in my DB in this format (dd-mm-yyyy).
Here I want to check the difference in days between the current date and the date in DB.
Here is my controller code:
public function index()
{
$domain_count = domain_details::get()->count();
//var_dump($domain_data);
$domain_alert = domain_details::
where('domain_ex_date','>',date('j-m-y'))
->get();
return view('home1')->with('domain_count' , $domain_count)
->with('domain_alert' , $domain_alert);
How do I achieve this? Is my approach right?
The above code shows 2016 is greater than 2017. I can see my logic is wrong but how do I change this?
It's better to have your dates in a DATE column in a proper format, otherwise MySQL won't know how to calculate it. Since you don't, you'll have to convert it with str_to_date, passing in the raw command:
where(DB::raw("str_to_date('domain_ex_date','%d-%m-%Y')"),'>',date('Y-m-d'))
I'm inserting date and time data in the database, my datatype is timestamp, I am inserting data using carbon but I always get this output from it '2014-11-25 00:53:48' I always get 00 on the hours, been stuck here for three hours... here is my code
$mydate=Carbon::now();
DB::table('attendances')
->where('user_id', Input::get('empid'))
->update(array('logon' =>$mydate));
try using $mydate->format("H:i")
Carbon defaults to outputting in DateTime format.
Also this looks like a simple use case: You could use DB::raw('NOW()') in place of $mydate if you are using MySQL
DB::table('attendances')
->where('user_id', Input::get('empid'))
->update(array('logon' =>DB::raw('NOW()')));
EDIT:
Also worth noting that Carbon extends php's DateTime. That means all DateTime functionality is still there. It also means your problem could be stemming from a problem with your PHP installation/configuration.