Laravel: Querying dynamically Time expressions - laravel

In order to list all the articles (films) that are included in our catalog the current month I have written the following query using the Laravel:
$current_month_film = DB::table('films')
->join('categories', 'films.category_id', '=', 'categories.id')
->select('films.*', 'categories.*')
->whereMonth('films.created_at', '=', '12')
->orderBy('films.created_at', 'desc')
->get();
It works perfect. It shows 5 films were added this month. The only problem is that I am hard coding December (month = 12). Next month I will need to update to month = 1. And so on each month; that is a bad solution.
The questions are:
1- How could I get always the current month? Trying
->whereMonth('films.created_at', '=', 'NOW')
give back not error, but the list comes empty. In December there are 5 films added.
2- I am showing a message in front end:
5 films added in Month 12
Is there a way to change the month = 12 into December and show a friendlier message like:
5 films added in December"
3- A better approach would be to show films included within the last 30 days. I did not find a time function for that.

Try to utilise Carbon which comes by default with Laravel.
->whereMonth('films.created_at', '=', Carbon::now()->month)
Since you know $month = 12, you can do something like
$someDate = Carbon::parse("2016" . $month . "01"); //someDate is a Carbon object now
$output = "added in Month " . $someDate->format('F');
Retrieve data 1 month old:
->whereBetween('films.created_at', [Carbon::today()->subMonth(), Carbon::today()])`
Edit: Put in use Carbon; before your class SomeClassName {. You might want to read up about Namespace

Related

Laravel, how to delete all records but the first one of that day

So I have a table to log profile followers every 10 minutes to keep a record of the increase/decrease.
However after the current day I only need to keep the last record of that day. Is there a simple way in Laravel to delete all records a part from the last one recorded every day.
I've tried searching and searching but comes up with nothing and feel like I'm going to create something overly complicated to accomplish this.
You'd need a query like this.
DELETE
FROM logs
WHERE id IN (
SELECT id
FROM logs
WHERE created_at BETWEEN 2022-02-28 00:00:00 AND 2022-02-28 23:59:59
ORDER BY created_at DESC
OFFSET 1
)
Assuming you have a date variable, you could make the query like this using the whereDate method:
$date = '2022-02-28'; // Y-m-d format. This is important.
DB::table('logs')
->whereIn('id', function ($sub) use ($date) {
$sub->select('id')
->from('logs')
->whereDate('created_at', $date)
->orderByDesc('created_at')
->offset(1);
})
->delete();

Getting records for the previous calendar month

I am trying to get the records of the previous month. That is say we are in February - I'd want to get records from 1st January to 31st January.
I tried:
$approved_reviews_lastMonth = ReviewHeader::where('created_at', '=', Carbon::now()->subMonth(1))->count();
But this does not get any for the last month.
Anyone?
Use format() to get the Year-Month format, and use like to get the previous month count.
$approved_reviews_lastMonth = ReviewHeader::where('created_at', 'like', Carbon::now()->subMonth(1)->format("Y-m")."%")->count();
You can use whereBetween as well.
$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString();
$lastDayofPreviousMonth = Carbon::now()->subMonth()->endOfMonth()->toDateString();
$approved_reviews_lastMonth = ReviewHeader::whereBetween('created_at', [$firstDayofPreviousMonth,$lastDayofPreviousMonth])->count();

Query between dates or matching date ranges in laravel and eloquent

I'm creating a page that displays the ongoing service orders of the current week. I can successfully query the database for tasks that happen between two dates, but the problem I am facing is this.
Let's say the current week starts on the 02/12 and ends on 08/12, and I have a service order that goes from 01/12 to 10/12, it surpasses the current week date range by one day in the start date and two days on the end date.
If I was able to make myself clear, How do I go about querying the database in order to retrieve service orders that are happening during the current week but the start and end dates that are beyond the current week range?
Heres the code I am using to query the database for SOs between dates:
->whereBetween("service_orders.initial_date", array($initialDate, $finalDate))
->orWhereBetween("service_orders.final_date", array($initialDate, $finalDate))
->where("service_orders.completed_date", "=", null)
->get();
Thanks for your help!
try this one,
->where("service_orders.initial_date", '<', $finalDate)
->where("service_orders.final_date", '>', $initialDate)
->where("service_orders.completed_date", "=", null)
->get();
Try this:
->where(function($q) use($initialDate, $finalDate){
$q->whereBetween("service_orders.initial_date", array($initialDate, $finalDate))
->orWhereBetween("service_orders.final_date", array($initialDate, $finalDate));
})
->where("service_orders.completed_date", "=", null)
->get();

Laravel, Carbon. Get count of hours for a specific month between dates

How to get the number of hours referring only to the one month between 2 dates?
For example, how to get count of hours for December for first or for second row at the screenshot?
I tried this (subMonths generated in the loop, so no worry about it):
$bookings = Booking::whereDate('departure_date', '>=', Carbon::now()->subMonths($i)->startOfMonth())
->orWhereDate('arrival_date', '<=', Carbon::now()->subMonths($i)->endOfMonth())->get();
and then:
foreach ($bookings as $book) {
echo Carbon::parse($book->departure_date.$book->departure_time)->diffInHours(Carbon::parse($book->arrival_date.$book->arrival_time));
}
But in this case I get count of hours for whole booking, how to get it only for December?
p.s. I need this for calculating the statistics (booking percentage).
You would likely need to ->addMonth() then go to the ->startOfMonth() then use diffInHours().
Carbon::parse($book->departure_date)
->addMonth()
->startOfMonth()
->diffInHours(Carbon::parse($book->arrival_date.$book->arrival_time));
I've omitted $book->departure_time otherwise the timestamp wouldn't be the first second of the first day of the month.

Laravel Eloquent Birthdays Query to get Date Column based on Date and Month only

I have a date() column in mysql which has the Date of Birth in mysql’s YYYY-MM-DD format:
$table->date('dob')->nullable();
I am trying to query this table so it lists all users who are having birthdays from today till next 7 days. I have something like this right now:
$date = new Carbon;
$today = $date->format('Y-m-d');
$futureDays = $date->addDays(7)->format('Y-m-d');
$birthdays = SiteUsers::where('dob', '>=', $today)
->where('dob', '<=', $futureDays)
->orderBy('dob', 'ASC')
->get();
The problem with the above query is that it only lists the users having DOB with the exact dates in this year only which is not right. What I really want is to list the users having birthdays irrespective of the year they were born by matching only the ‘date’ and ‘month’ and ignoring the ‘year’.
I don’t know how to achieve that. Can someone help me out please…
Shortly after I posted my question, I tried a method using raw queries that uses DateOfYear() SQL Function. So this is what I have now which seems to be working by getting the users with birthdays in the next 7 days irrespective of the year:
$birthdays = SiteUsers::whereRaw('DAYOFYEAR(curdate()) <= DAYOFYEAR(dob) AND DAYOFYEAR(curdate()) + 7 >= dayofyear(dob)')
->orderByRaw('DAYOFYEAR(dob)')
->get();
enjoy

Resources