Using Carbon in Eloquent Query - php

Good day everyone,
I'm currently realising a system that lets colleagues fill in their worked hours and what they worked on. I save those into the database using a time_stamp (date) named in the table. Now I have been trying to get the values of the filled in registrations of last week (I created some dummy times). And I have been trying to use Carbon and the Eloquent query builder at the same time, and i'm completely stuck. Would anyone mind to help me out?
$currentDate = \Carbon\Carbon::now('GMT+2');
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
$weekly = Hoursregistration::pluck('date')->agoDate($currentDate);
return $weekly;
Is the code that should pick up the dates from the db (which works). But when I try to put in the variables containing the carbon methods. It doesnt work and throw me a Method agoDate does not exist. (View: /var/www/clients/client0/web319/web/resources/views/hoursregistrations/index.blade.php) error.
I would love some help as this is crucial to my education (kind of in a tight spot rn.)

As you ask for: all Hoursregistration records from 1 week ago until now
// Current date + GMT(+2) as stated in your question
$currentDate = Carbon::now('GMT+2');
// Date exactly 1 week ago
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
// Records with date -between- two values
// $weekly = Hoursregistration::whereBetween('date', [$agoDate, Carbon::now('GMT+2')])->get();
// Or even simpler, all records where date is 'higher' than 1 week ago
$weekly = Hoursregistration::where('date', '>', $agoDate)->get();
// Getting the dates with the `pluck` method on the returned $weekly collection
$dates = $weekly->pluck('date');
return $weekly;

Related

Laravel - select rows from previous week on monday

I have a table mdl_forum_posts with a field created that's a BIGINT (database is not mine, so don't blame for the type of field). An example of value is 1504170577. The value is saved as a timestamp.
There will run a cron every Monday (first day of the week) that needs to select all the rows created in the previous week (created value in week before).
I'm trying to do this:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
$postsNL = DB::table('mdl_forum_posts')->whereBetween('created', array($agoDate,$currentDate))->get();
But this isn't returning any rows (and it should!).
Keep in mind that when you do some operations on a Carbon object it will modify the instance of the object itself, so basically when you run the statement
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
you are also modifying $currentDate.
The below code should do the trick:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->copy()->subDays($currentDate->dayOfWeek)->subWeek()->setTime(23, 59, 59);
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
The copy method will make all the modifications on a copy of the Carbon instance, not affetting the original one.
Hope it helps
Why should it? MySQL won't just compare an integer to a date. The integers are called unix timestamps and you can easily get unix timestamps out of Carbon by using the timestamp property on a Carbon instance:
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
Since Carbon extends DateTime, you could also use the getTimestamp method.

Counting database for previous month across the new year roll over PHP SQL

I have had a custom wordpress plugin that runs a report for the database entries from the previous few months, and it worked all year, but now that the new year has happened, it shows no results because it is counting back a few months but then keeping it for 2016.
For example, I load the page on Jan 1st 2016, and it shows the results for December 2016 instead of 2015 when I am using the following method for getting last month's data.
$today = date("Y-m-d H:i:s");
$month_current_start = date("Y-m-")."1 0:0:0";
$currentmonth = date("m");
$lastmonthnum = $currentmonth - 1;
$last_month_start = date("Y-").$lastmonthnum."-1 0:0:0";
$last_month_end = date("Y-").$lastmonthnum."-31 0:0:0";
so then I have an SQL that says something like
$var = $wpdb->get_var( "SELECT Count(*) FROM `table` WHERE table.timestamp BETWEEN '$last_month_start' AND '$last_month_end' AND table.amount = 1200" );
Any tips on how to fix this query so that it knows that last month is 2015?
I'm no professional so I'd love beginner-style help :-)
I can make it work manually but i'd like the code to work for the next few months automatically (since the actual plugin calculates the last four months).
Easiest way would be to convert last month to a time stamp, and use that for creating the format you have in your DB. An example based on what you have so far would be:
$today = date("Y-m-d H:i:s");
$month_current_start = date("Y-m-")."1 0:0:0";
$ltime = strtotime("-1 month");
$last_month_start = date("Y-m",$ltime)."-1 0:0:0";
$last_month_end = date("Y-m",$ltime)."-31 0:0:0";
What this does, is it makes a timestamp for 1 month ago from when it is called in the line $ltime = strtotime("-1 month"); From there, it makes the format for the first day and last day of the month (assuming there are always 31 days of course ^^) based on the timestamp, which you'll use to provide the year and the month.
PHP Sandbox with the code example and it's output if you'd want to play around with how strtotime works.
In mysql you have the option to use year_month, see this for reference.
Get the current year and month using your code
update your query accordingly
or you can have your sql server do all the work for you by using the date_add function
Update your question with the db server you are using, then I can write the new query for you.

Change returning date from Propel in PHP

I have a Database and I use Propel to get the data.
Now I have the following problem:
I want to get the date from one Table and add 30 days on it.
So something like this:
$invoicePayDay = $invoice->getCreationDay()->add(30 days)->format('d.m.Y');
I know that I can read the month, day and year separately and can than add 20 days and create a date from it again. but properly there is a better way to do it with Propel like my example?
Return the date as a var than you can do
$date = date('d.m.Y', strtotime('+30 days', strtotime($returnDate)));

How can I select all Eloquent models from a MySQL database inserted today, within the last week or the last month?

I have an Eloquent Model (Test) associated with a MySQL table called tests, with the following structure:
tests
id int
created_at date
updated_at date
correct boolean
I am trying to select only those tests created today, within the last 7 days and within the last month, something like this (pseudocode):
$todays_tests = Test::where('created_at','=', 'today');
$this_weeks_tests = Test::where('created_at','=', 'last 7 days');
$this_months_tests = Test::where('created_at','=', 'last month');
I'm sure Laravel provides an easy way to do this but I'm not sure how best to go about it. Presumably I need to use a raw MySQL query?
Many thanks,
I am sure you can do some nice things with the Carbon plugin. The Carbon documentation: https://github.com/briannesbitt/Carbon
For example for created today, if you add this in your Test model:
public function scopeCreatedToday($query)
{
return $query->whereBetween('created_at', array(Carbon::today(), Carbon::today()->addDay()));
}
You will be able to do: $tests = Test::createdToday()->get();.

Query to get rows with a UNIX Timestamp of today

In my DB I have UNIX Timestamps as due dates for jobs that need to run. On a given day or a given hour I'd like to know which jobs need to run. I have the following code to query my jobs table:
$job = Model_Job::find('first',
array(
'where' => array(
array('status_id', 1), // active
array('due_date', today)
)))
The last array is just pseudo code of course. I came up with the following code to figure out if a timestamp is today.
date('Ymd', strtotime(Date::forge(time())->get_timestamp())) == date('Ymd', strtotime($job->due_date))
How would I combine that with my query? Is there a better way then looping through the queried array?
Now, this is probably not a good way but it was the first that came to mind.
$today = strtotime('today 00:00');
You can use the date from that snippet and set a WHERE due_date > $today I'm not quite sure how to do that with your database model.
edit: This relies on that you have correct timezone settings in your php configuration.
As sebastian pointed out, this will get all future dates also, but you could simply use the same technique to get the last timestamp of the day
$todaystart = strtotime('today 00:00'));
$todayend = strtotime('today 23:59:59'));
and the use a BETWEEN operator in your SQL-query

Categories