convert raw query in laravel eloquent way - laravel-5

How to convert this query in Laravel eloquent way?
SELECT * FROM posts WHERE status=1 and now() BETWEEN start_time and end_time ORDER BY id DESC LIMIT 1
// What so far i have tried
Post::whereStatus(1)->orderBy('id','desc')->get()
"and now() BETWEEN start_time and end_time" .I am unable to convert
this part in eloquent way.
Any suggestion would be highly appreciated.

You can do the following
Post::where('status', 1)
->where('start_time', '>', Carbon::now())
->where('end_time', '<', Carbon::now())
->orderBy('id', 'DESC')
->take(1)
->get();

You can achieve the same semantic by defining that your start_time is lower than the current datetime and your end_time is greater than it:
Post::whereStatus(1)
->where("start_time", "<", Carbon::now())
->where("end_time", ">", Carbon::now())
->orderBy('id','desc')
->first();

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();

Fetch records that matches month and year using Laravel eloquent

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();

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();

cast datetime to date

I'm doing a whereBetween dates query on Eloquent. However, I have an issue with the date time.
If I select date_from to 2018-11-01 and date_to to 2018-11-29
and if I have a data that was created on 2018-11-29 12:28:45 the data created on this datetime will not be included because of the time.
Is there a way to cast the created_at to date?
here's my code:
Payable::with('details', 'transaction_type')
->whereBetween('created_at', [$request->date_from, $request->date_to])
->get();
You can set time to your date variables.
$request->date_from = $request->date_from . ' 00:00:00';
$request->date_to = $request->date_to . ' 23:59:59';
I feel a much cleaner way to handle dates in Laravel is using the Carbon package.
$date_from = Carbon::createFromFormat('Y-m-d', $request->date_from)->startOfDay();
$date_to = Carbon::createFromFormat('Y-m-d', $request->date_to)->endOfDay();
Just FYI, created_at column when accessed via eloquent will return a carbon date object by default.
Hope this helps.
K
If you don't mind adding an extra -> to your querying, you can very easily do this:
Payable::with('details', 'transaction_type')
->whereDate('created_at', '>=', $request->date_from)
->whereDate('created_at', '<=', $request->date_to)
->get();

Resources