Laravel, filter timestamp by date only - php

I want to filter a table by user ID and the created_at field. The only thing is created_at is a timestamp, and I want to query by date only not time.
So something like -
$messages = Message::where(['from' => $fromUser->id, 'created_at' => 'TODAY'S DATE'])->get();

$query->whereDate('created_at', '=', date('Y-m-d'));
or
$query->whereDate('created_at', '=', Carbon::today()->toDateString());

The only way I know (in Laravel) to compare a DATE against created_at is to use whereRaw, so for your example, you'd use something like:
Message::where(...)->whereRaw('DATE(created_at) = ?', [$today])->get();
You can find more information about Eloquent and it's other methods here

Related

Date range search in laravel controller

Suppose I have two data rows in my orders table.
`order1 created at 2022-06-18`
`order2 created at 2022-06-19`
Now while I want to search within 2022-06-18 and 2022-06-19 date it shows only order1, but not showing order2 though order2 is also created at 2022-06-19 date.
But If I search within 2022-06-18 and 2022-06-20 then both order1 and order2 row will return as a result.
Here is my laravel query in controller
DB::table('orders')
->whereBetween('orders.created_at', [$from_date, $to_date])
->get();
Is there any problem? Any body help please?
Between always is inlcuding.
In your case the createdat >= '2022-06-18' and <= '2022-06-20'.
Therefore both rows are included
The default created_at and updated_at "timestamp" field created by laravel migration are of type DateTime not just Date.
When you run
->whereBetween('orders.created_at', ["2022-06-18", "2022-06-19"])
It is equivalent to
->whereBetween('orders.created_at', ["2022-06-18 00:00:00", "2022-06-19 00:00:00"])
But your Order2 has created_at with a different hour/minute/second than "00" on the date "2022-06-19".
That's why you get only one result.
To fix it, either add one day ["2022-06-18", "2022-06-20"] or specify the hour/minute/second.
->whereBetween('orders.created_at', [
date('Y-m-d 00:00:00', strtotime($from_date)),
date('Y-m-d 23:59:59', strtotime($to_date)),
])

Ordering records using dates in Laravel eloquent

I have a column move_out that stores date in this format - m/Y e.g 02/2020. I want to order the records in that table by the move_out column in descending order but my solution don't seem to be working. It does not arrange the records appropriately. This is what I am doing.
$data = User::orderBy('move_out', 'DESC')->get();
How do I solve this?
The datatype for the move_out column is string.
try STR_TO_DATE
$data = User::orderBy(DB::raw("STR_TO_DATE(CONCAT('01-', move_out),'%d-%m/%Y')"), 'DESC')->get();
Try to use DATE_FORMAT:
$items = DB::table("users")
->orderBy(DB::raw("DATE_FORMAT(move_out,'%M/%Y')"), 'DESC')
->get();

Laravel datetime created_at

I have a question. If created_at in my database is datetime and I want to make a query like this
whereDate('created_at', '=', date('Y-m-d'))
I get nothing as a result. How can i handle this situation ?
Another case: I want
whereDate('created_at', '=', date('M'))
You can use other helper functions maybe:
$query->whereYear('created_at', '=', date('Y'))
->whereMonth('created_at', '=', date('m'))
->whereDay('created_at', '=', date('d'));
Assuming you are using MySQL, you could use whereRaw:
whereRaw('created_at = CURDATE()')
For your second case:
whereRaw("month_name = DATE_FORMAT(CURDATE(), '%b')")
First Query: You can use Carbon specifying date format (date without time toDateString() / date with time toDateTimeString() ).
$query->whereDate('created_at', '=', Carbon::today()->toDateTimeString());
Second Query: Just query on whereMonth
$query->whereMonth('created_at', '=', date('m'));

Laravel : Order by string date using query builder with MySql

The table have a startDate column which is VARCHAR type, so need to get rows by ascending order using this column.
Tried this :
orderBy(DB::raw("DATE(startDate)"), 'ASC')
the above does not return correct order, how to pass string date in order by clouse?
Example:
'startDate' => '07-Nov-2017'
$items = DB::table("mytable")->orderBy(DB::raw("DATE(startDate)"), 'ASC')->where('userId','=',$userId)->get();
You need to convert the date to MySQL format. Try to use DATE_FORMAT:
$items = DB::table("mytable")
->orderBy(DB::raw("DATE_FORMAT(startDate,'%d-%M-%Y')"), 'ASC')
->where('userId','=',$userId)
->get();
Gunaseelan was right, but with synthax errors, try this :
$items = DB::table("mytable")->where('userId','=',$userId)->orderByRaw("DATE_FORMAT('d-m-Y',startDate), ASC")->get();

Symfony get distinct months from database DateTime field

Currently I have a Query Builder which gets all distinct dates from DateTime field but I need to get only distinct months and years and ignore the days. For example if dates where 2015-06-15, 2015-06-20, 2015-07-10, 2016-06-13 I should get 2015-06, 2015-07, 2016-06.
Is there any way to get this result right from database or do I need to this with php?
My current query looks like this:
$dates = $this->getEntityManager()->getRepository('EventBundle:Event')
->createQueryBuilder('e')
->select('e.startDate')
->where('e.startDate >= :startDate')
->setParameter('startDate', new DateTime('now'))
->orderBy('e.startDate', 'ASC')
->distinct()
->getQuery();
$dates = $dates->getResult();
You can get it from the database but I think you will need to use a native mysql query e.g.
select distinct(DATE_FORMAT(e.startDate,'%Y-%m'))
from event e
where e.startDate >= :startDate
To perform a native query see How to use Doctrine DBAL

Categories