extract the month number from stored dates Laravel - php

I'm working on a project where users insert their workout every day .
Each user can insert their workout date choosing from a calendar storing it in Exercise table in Date form.
I've written this to calculate the workout days in the current month
DB::table('exercises')
->select('day')
->where('user_id', Auth::user()->id)
->whereMonth('day', date('m'))
->whereYear('day', date('Y'))
->distinct()
->get()
->count()
and I want to display for each user the month with the highest workout days, I can do so with storing every month's workout days in a separate table but I don't know how to only extract the month from the dates already stored

You can use Carbon e.g below
$month = Carbon::parse("2022/06/12")->format('MM');
you can read more about this at Carbon Documentations

$month= date('M', strtotime($yourdate)
This should give you the month only from a stored date value. If you already have carbon installed and imported in your controller, I would suggest following #terinao given answer since it enhances a lot of features you would otherwise not find in standard php date functions.

Try this solution
use Carbon\Carbon;
...
$current_month = Carbon::now()->format('m');
$current_year = Carbon::now()->format('Y');
DB::table('exercises')
->select('id', 'day')
->where('user_id', Auth::user()->id)
->whereMonth('day', $current_month)
->whereYear('day', $current_year)
->distinct()
->count();

Related

how to compare today to another date with where

I need to compare today to the date twenty business days after from created_at. I have afterTwentyBusinessDays function. Is it possiple to use it with where in laravel?
->where(afterTwentyBusinessDays($created_at), today())
You have to get a date that was twenty days ago and then set in where condition
->whereDate('created_at', date('Y-m-d', strtotime('-20 days')));
I presume afterTwentyBusinessDays($created_at) return carbon date time object.
Try $query->whereDate('created_at', '>', afterTwentyBusinessDays($created_at))
The most efficient way is to use carbon
now()->diffInDays('2023-1-23 07:06:31') // 19
now() will give you carbon instance alongwith UTC date and time. You can compare any dates, years, months, months, weeks even seconds.
Explore Carbon docs or visit detailed Carbon methods and their uses
https://www.digitalocean.com/community/tutorials/easier-datetime-in-laravel-and-php-with-carbon
Why you are not using Eloquent Model's own predefined methods to compare date and times like whereDate(), whereDay(), whereMonth() or wheryear() there are many.
Also you can play with these days, remember to parse in your timezone and format
User::whereDay('created_at', '>', '2023-1-23 07:06:31')->get();

Filter available time slot for today in laravel using carbon

I want to filter available time for today for a user. He can only make an appointment for a time slot that is bigger than time right now + 6 hours. But the problem is when + 6 hours transfers to the next day so it could be like 00:44 next day and in that case when it compares to the time slots it shows that time slot at 8:00 for example is bigger than 00:44 so it shows that time slot for today although it shouldn't be possible to make an appointment for that time slot anymore. Is there a way to filter it in the eloquent? I basically want addHours to stop if it reaches 23:59. My Eloquent function:
$times_today = TimeSlot::where('status', 1)
->whereTime('time', '>', Carbon::now()->addHours(6))
->get();
Carbon provides a tomorrow() function that you can use in the same way you've made use of now().
I assume you don't want people booking appointments up until midnight (although perhaps you do?) so I would also use the subHours() function to limit timeslots to before a certain time.
$times_today = TimeSlot::where('status', 1)
->whereTime('time', '>', Carbon::now()->addHours(6))
->whereTime('time', '<', Carbon::tomorrow()->subHours(2))
->get();
You can create timestamp for specfic time using create function with time zone then you can aad hours in current timestamp by using Carbon::now()->addHours(6)
$dtToronto = Carbon::create('2022','8','2', 23,59,59, 'America/Toronto');
$times_today = TimeSlot::where('status', 1)
->whereTime('time', '>', Carbon::now()->addHours(6))
->whereTime('time', '<=', $dtToronto)->get();

laravel eloquent with multiple where conditions issue

In my laravel based application's database, I have a table to store records of the user payments.
I'm having created_at column to store the record creation date and payment_annum column to store the subscription type(monthly or yearly)
Now I'm trying to display those records on my admin dashboard blade. But the thing is i only need to display the last month's, MONTHLY subscription records only.
So far I could retrieve data where the subscription type is monthly but struggling to filter it by the last month..
This is my current eloquent, where only checks the subscription type
$get_monthly_payments_lastmonth=AppPayment::where('payment_annum','=','monthly')
->get();
So how can I check the 'last month' condition as well
try changing your eloquent to this,
$get_monthly_payments_lastmonth=AppPayment::where('payment_annum','=','monthly')
->whereMonth('created_at', '=', Carbon::now()->subMonth()->month)
->get();
this would give give you the last month records where the payment_annum is monthly
Do you want your query to return all elements created in the last month (as of today: created_by matching 2020-03-*) or rather created during the last month (created_by >= 2020-03-23)?
For March, extend the accepted solution by
$get_monthly_payments_lastmonth=AppPayment::where('payment_annum','=','monthly')
->whereMonth('created_at', '=', Carbon::now()->subMonth()->month)
->whereYear('created_at', '=', Carbon::now()->subMonth()->year)
->get();
For the latter, this should do:
$get_monthly_payments_lastmonth=AppPayment::where('payment_annum','=','monthly')
->whereDate('created_at', '>', Carbon::now()->subMonth())
->get();

Get records within a specific timeframe in Laravel

On my website, I use Laravel's created_at to store the time at which images are uploaded.
However, I want to be able to create a query that gets images only within a specific time frame.
Those would be:
-The past 24 hours
-The past week
-The past month
-The path year
I was thinking of something like...
$images = Images::where('created_at', '>=', Carbon::now()->hours(24))->get();
It would be easy to get records from within specific hours, since I could simply go from 24 to 168 to 672 to 2087 (day, week, month, year).
Thoughts?
Use sub methods:
Images::where('created_at', '>=', Carbon::now()->subDay())->get();
Images::where('created_at', '>=', Carbon::now()->subWeek())->get();
Images::where('created_at', '>=', Carbon::now()->subMonth())->get();
Images::where('created_at', '>=', Carbon::now()->subYear())->get();
Or:
Images::where('created_at', '>=', Carbon::now()->subHours(24))->get();

Counting distinct days from DateTime in MySQL

I have DB table that logs request with an IP column and a DateTime stamp. I'm trying to fetch this data in a way that makes me count the number of days a certain IP has made requests. I'm using Laravel's query builder.
So far, this is what i've got:
$data = DB::table('requests')
->groupBy('ip')
->select('ip',
DB::raw('COUNT(DISTINCT created_at) as days'),
DB::raw('COUNT(*) as requests'))
->orderBy('days', 'desc')
->take(50)
->get();
My problem is that the timestamp also holds hours, minutes and seconds. So the "days" count will be about the same as the number of total requests. I want to only count the number of days active.
If field created_at is TIMESTAMP:
COUNT(DISTINCT FROM_UNIXTIME(created_at, '%Y-%m-%d')) as days
or if field is DATETIME:
COUNT(DISTINCT DATE(created_at)) as days
You can probably use DATE_FORMAT to do what you want.
Take a look at this question:
Selecting a distinct date by day only from datetime (YYYY-MM-DD HH:MM:SS) in MySQL

Categories