laravel get entries of last month, displaying them day by day - laravel-5

What's the best way to get all records from the last month, day by day using the default laravel "created_at" as timestamp of creation.
Is there some way to prevent needless database load, when loading them?
database design is laravel "basic"
id|name|created_at|updated_at

I've found this article regarding date filtering.
$q->whereDay('created_at', '=', date('d'));
$q->whereMonth('created_at', '=', date('m'));
$q->whereYear('created_at', '=', date('Y'));

Related

Get data for Last 7 days from database for each day in laravel

Good Evening.
I am trying to get the data from database for Only for last 7 days and show the same in table.
I tried the below code, but its giving me data for 30 days. I am new to coding and a self learner,
Your help will be helpful...
controller code
$sevendays = Carbon::now()->subDays(7);
$dairymilksaleweek = customermilksale::selectraw('(saledate) as "startdate", (SUM(buffalomilk)) as "totalbmilk", (SUM(a2milk)) as "totala2milk", (SUM(jerseymilk)) as "totaljmilk", (SUM(totalmilk)) as "totalmilk"')
->whereDate('saledate', '>=', now()->subDays(7)->startOfDay())
->groupBy('saledate')
->orderBy('saledate')
->get();
Thanks in advance...
As per your query you wanted to get data for last seven days and you are using the whereDate() method of laravel eloquent which needs dates in specified format i.e format('d/m/Y') don't know what's the format for your saledate column but you need to convert second parameter of the function to one of the below.
1- today()->subDays(7)
2- now()->subDays(7)->startOfDay()->format('d/m/Y')
Hope this will help you out.

Laravel get all records that are 19 days ahead of timestamp not firing

I am trying to send a followup email to users using Laravel.
The conditions of the email are that any users that have a status of followup will get an email 19 days from when the recorded timestamp was added. I am doing this via a daily cronjob, but it doesnt seem to be firing and I think it is because of the query to get the users in the first place.
For example, if the date recorded is 02/12/2021, the email should be sent to them on 21/12/2021
The query is as follows;
App\Users::query()
->where('status', 'followup')
->where('recorded', now()->addDays(19))
->get();
Instead of adding days,you should substract days from current date.
now()->subDays(19) instead of now()->addDays(19)
App\Users::query()
->where('status', 'followup')
->where('recorded', now()->subDays(19))
->get();

Laravel where date - what does it actually do? Should I Carbon::parse it?

I set up a laravel api to take a couple date strings as query parameters,
So for example I would do this in my javascript:
axios.get(`/apiuser/${this.state.user.id}/request-breakdown.json?start=${encodeURIComponent(start.toISOString())}&end=${encodeURIComponent(end.toISOString())}`)
Sending through start and end query parameters as ISOString dates
Now, on the laravel side of things, my initial idea was to Carbon::parse these dates
Model::where('created_at', '>=', Carbon::parse($request->get('start')))
->where('created_at', '<', Carbon::parse($request->get('end')))
But I played around a little bit and I discovered I apparently didn't need the Carbon::parse at all:
Model::where('created_at', '>=', $request->get('start'))
->where('created_at', '<', $request->get('end'))
As far as I can tell, both of those results are correct.
I just wanted to know, what's the correctly Laravel way? And are there advantages to one way over another? For example, maybe I should be using Carbon::parse because it will allow me to accept more formats of dates to be passed through?
I'm only going to answer from personal experience as I don't have the SQL know-how to explain why it happens in depth. I've stopped using where('date', '>=', date) because the results can be a bit erratic. I suppose this is due to how dates are stored, sometimes we have date formats and datetime formats and sometimes the input dates are different.
It seems like using whereDate('date', '>=', Carbon::parse(date)) provides the most reliable returns. There are post stating that whereDate() wraps the column in the table with DATE() function, so it is a little more taxing on resources. Since you are already passing the dates in ISOString that is probably why you are not seeing any real world impact, but if you were trying to query for 08-02-2019 I would suggest using Carbon.

Laravel DB:table created_at Date Is Different from DB

Running Laravel 5.6, I found this oddity:
> php artisan tinker
> App\Users::all();
...
created_at: "2018-06-04 16:26:00",
updated_at: "2018-06-04 16:26:00",
....
Pulling in the same element within a Laravel model using:
$users = DB::table('users')->get();
$users->first()->created_at
//2018-04-06 15:59:01
This is the same row. The 35 minute delay is odd, but perhaps due to Homestead latency(?) I have no idea why the month and day are rearranged.
In my middleware, I set the locale information as such:
setlocale(LC_TIME, env('APP_LOCALE_CODE')); //de_DE.UTF-8
date_default_timezone_set(env('APP_LOCALE_TIMEZONE')); //APP_LOCALE_TIMEZONE=Europe/Berlin
Anyone have an idea here?
Turns out the query I needed required multiple joins and groupby sorting so I used DB::table instead of eloquent. When doing so, you need to be careful of the select statement, especially with common DB fields like created_at. Essentially it was pulling in another "created_at" field and by luck, happened to be a reverse of todays current date causing the initial thought it was a formatting error.

Getting records only if eager loaded condition met in laravel elequent

I'm using Laravel 5.3.30 and facing the current problem. I tried to search everywhere and did not find any related solution to what I exactly need. So please before mark this as duplicate make sure you read my question carefully.
Tables: [clients], [messages]
Relation: clients has many messages
What I'm trying to achieve is:
Getting all clients who his last message (contact_date) is less than 1 week from now.
I tried many things including the following:
Client::whereHas('messages', function($query){
$query->orderBy('contact_date', 'desc')
->whereDate('contact_date', '<', Carbon::now()->subDays(7));
})->get();
This is the best option I have tell now, but it is not satisfy my needs.
This will check for all (contact_date)s of a client and will retrieve any client who have a message less than the required date.
My question is:
How I can apply this only for the latest [messages] record? Suppose I have 100 messages for each client and want to apply this only on the latest message. So, if the message condition does not met, the query will not retrieve the client.
It looks like you need to do a subquery to join only dates older than specified date:
Client::select('clients.*')
->join(DB::raw('(SELECT messages.* FROM messages WHERE contact_date < {$date})'), function($join)
{
$join->on('clients.id', '=', 'messages.client_id');
})
->groupBy('messages.client_id')
->orderBy('contact_date', 'desc')
->get();
I'm not sure this code will work perfectly as is but it should give you an idea of how to do it.
You should use > in your condition:
whereDate('contact_date', '>', Carbon::now()->subDays(7));
Full code here:
Client::whereHas('messages', function($query){
$query->orderBy('contact_date', 'desc')
->whereDate('contact_date', '>', Carbon::now()->subDays(7));
})->get();

Resources