Fetch records that matches month and year using Laravel eloquent - laravel-5

How do I query a table such that it only fetches records that matches a particular month and year e.g. Y-m i.e. 2020-10. of the 'created_at' column.
This is what I am currently doing:
School::where('user_id', 1)->where('created_at', '=', '2020-10')->count();

I would suggest to create a date range for your filter so this way your query will remain sargable
$date = \Carbon\Carbon::parse($year."-".$month."-01");
$start = $date->startOfMonth()->format('Y-m-d H:i:s');
$end = $date->endOfMonth()->format('Y-m-d H:i:s');
School::where('user_id', 1)
->whereBetween('created_at', [$start, $end])
->count();

Related

How to write SQL Function where YEAR(<date_column_name>) in laravel controller

I want to fetch data from database which has booking year is 2022, and the column I have is tanggal_take whose value format is 'Y-m-d', so I want to use SELECT * FROM table_name WHERE YEAR(tanggal_take) = "2022"; How to write it in laravel controller using Eloquent?
here is my code now
$data = Booking::join('users', 'users.id', '=', 'bookings.id_member')
->join('packages', 'packages.kode_paket', '=', 'bookings.kode_paket')
->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range )
->get(['bookings.*', 'packages.*', 'users.*']);
The result is 0 but in database i have 4 datas with year 2022. I also already change ->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range ) to ->whereYear('bookings.tanggal_take', '=', $request->range ) but still 0 result. Any hint? I will also looking for documentation by my self rn. Thanks

How to get data which has expiry date nearest to current date?

I have PurchaseOrderProduct Model from which I am getting data like that
PurchaseOrderProduct::with('products')
->with('warehouse_locations')
->with('productStatuses')
->with('purchase_orders')
->where('product_id', $request->product_id)
->where('free_qty', '>=', 1)
->get();
Now in this table, I have the column expiry_date of type date i want to fetch data orderBy expiry_date nearest to the current date .
Means purchase_order_product whose expiry date is nearest to current date should come first.
$product = PurchaseOrderProduct::with('products')
->with('warehouse_locations')
->with('productStatuses')
->with('purchase_orders')
->where('product_id', $request->product_id)
->where('free_qty', '>=', 1)
->whereDate('expiry_date', '>', Carbon::now())
->orderBy('expiry_date','asc')
->get();

Laravel where age clause

I have a Student model and it has properties such as full_name, birthdate, ...
birthdate is a date type column.
how can I filter my students and find those students with more than 20 years old?
something like:
$students = Student::whereAge('birthdate', '>=', 20)->get();
You cannot use whereAge as Age should be a column that exists in your database in that case.
You can try this instead:
$students = Student::whereYear('birthdate', '>=', now()->subYears(20)->year)->get();
Even better maybe to compare the exact date 20 years ago:
$students = Student::whereDate('birthdate', '>=', now()->subYears(20))->get();
Using raw SQL:
$students = Student::whereRaw('TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 20');
You can remove -20 years from today's date, and then compare it to the birthdate. Like so:
$date = date('Y-m-d', strtotime(date('Y-m-d').' -20 year'));
$students = Student::whereDate('birthdate', '<', $date)->get();

search dates with laravel not between query

I have to search for data with given dates and time (morning and evening). How can I find available dates from data with laravel query?
If i search dates 2019-06-10 to 2019-06-18. It should only return id 3 and 4. In this query, it is returning id 1, 3 and 4. What's wrong with this query it is not checking from in between dates? I have date type column in the database for start and end date.
I want to check two conditions
Given dates should be not equal to date_from and date_to
Given dates are not between in these dates
Both conditions in same query. Hope you understand.
id event_id date_from date_to
1 1 2019-06-08 2019-06-12
2 1 2019-06-14 2019-06-16
3 2 2019-06-20 2019-06-25
4 3 2019-07-26 2019-07-27
$getEvents = Booking::where('category_id', '=', $categoryID)
->where('date_from', '!=', $startDate)
->where('date_to', '!=', $endDate)
->orWhere('date_from', '<', $startDate)
->orWhere('date_to', '>', $endDate)
->whereNotBetween('date_from', [$startDate,$endDate])
->whereNotBetween('date_to', [$startDate,$endDate])
->get();
Try this
DB::table('table_name')
->whereNotBetween('date', [star_date, end_date])
->get();
Assuming that $endDate will always be greater (or equal) than $startDate
$startDate = "2019-06-10";
$endDate = "2019-06-18";
Given dates are not between in these dates
->whereDate('date_to', '<', $startDate)
->whereDate('date_from', '>', $endDate)
If given $startDate is greater than db 'date_to', $startDate is not between 'date_to' and 'date_from'. Will retrieve records with 'date_to' less than "2019-06-10".
And when the given 'date_from' is greater than $endDate, $endDate is not between 'date_to' and 'date_from'. Will retrieve records with 'date_from' greater than "2019-06-18".
Given dates should be not equal to date_from and date_to
This is not needed since in the query of point 2, we use > and <, which will not take into account equals.
//->where('date_from', '<>', $startDate)->where('date_from', '<>', $endDate)
//->where('date_to', '<>', $startDate)->where('date_to', '<>', $endDate)
Just:
$getEvents = Booking::where('category_id', '=', $categoryID)
->whereDate('date_to', '<', $startDate)
->whereDate('date_from', '>', $endDate)
->get();
Laravel 5
$getEvents = Booking::where('category_id', '=', $categoryID)
->where('date_from', '<', $startDate)
->where('date_to', '>', $endDate)
->get();

laravel queries calculating average

I want an average of all sales for the month of January in the whole table. My date_sold is in the format y/m/d. I may have many records eg 2016-01-23, 2015-01,14, 2017-01-05 all with their sales.
I want to get the average of the sales for a particular drug or drugs if they were sold in January. So far this is my controller but it is only picking the first record
$drug = $request->get('drug');
$stocks = DB::table('sales')
->join('drugs', 'drugs.id', '=', 'sales.drug_id')
->select('sales.*','drugs.name', DB::raw ('AVG(sales.quantity_sold) as average_sales'))
->whereIn('drug_id', $drug)
->whereMonth('complete_sold','=', Carbon::today()->month)
->get();
Add groupBy:
$drug = $request->get('drug');
$stocks = DB::table('sales')
->join('drugs', 'drugs.id', '=', 'sales.drug_id')
->select('sales.*','drugs.name', DB::raw ('AVG(sales.quantity_sold) as average_sales'))
->whereIn('drug_id', $drug)
->whereMonth('complete_sold','=', Carbon::today()->month)
->groupBy('drugs.id')
->get();

Resources