Get only records created today in laravel - mysql

How do I use the created_at field to get only the records that were created today and no other day or time?
I was thinking of a ->where('created_at', '>=', Carbon::now()) But Im not sure that would work.

For Laravel 5.6+ users, you can just do
$posts = Post::whereDate('created_at', Carbon::today())->get();

Use Mysql default CURDATE function to get all the records of the day.
$records = DB::table('users')->select(DB::raw('*'))
->whereRaw('Date(created_at) = CURDATE()')->get();
dd($record);
Note
The difference between Carbon::now vs Carbon::today is just time.
e.g
Date printed through Carbon::now will look like something:
2018-06-26 07:39:10.804786 UTC (+00:00)
While with Carbon::today:
2018-06-26 00:00:00.0 UTC (+00:00)
To get the only records created today with now can be fetched as:
Post::whereDate('created_at', Carbon::now()->format('m/d/Y'))->get();
while with today:
Post::whereDate('created_at', Carbon::today())->get();
UPDATE
As of laravel 5.3, We have default where clause
whereDate / whereMonth / whereDay / whereYear
$users = User::whereDate('created_at', DB::raw('CURDATE()'))->get();
OR with DB facade
$users = DB::table('users')->whereDate('created_at', DB::raw('CURDATE()'))->get();
Usage of the above listed where clauses
$users = User::whereMonth('created_at', date('m'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->month;
//select * from `users` where month(`created_at`) = "04"
$users = User::whereDay('created_at', date('d'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->day;
//select * from `users` where day(`created_at`) = "03"
$users = User::whereYear('created_at', date('Y'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->year;
//select * from `users` where year(`created_at`) = "2017"
Query Builder Docs

If you are using Carbon (and you should, it's awesome!) with Laravel, you can simply do the following:
->where('created_at', '>=', Carbon::today())
Besides now() and today(), you can also use yesterday() and tomorrow() and then use the following:
startOfDay()/endOfDay()
startOfWeek()/endOfWeek()
startOfMonth()/endOfMonth()
startOfYear()/endOfYear()
startOfDecade()/endOfDecade()
startOfCentury()/endOfCentury()

with carbon:
return $model->where('created_at', '>=', \Carbon::today()->toDateString());
without carbon:
return $model->where('created_at', '>=', date('Y-m-d').' 00:00:00');

You can use
whereRaw('date(created_at) = curdate()')
if the timezone is not a concern or
whereRaw('date(created_at) = ?', [Carbon::now()->format('Y-m-d')] )
otherwise.
Since the created_at field is a timestamp, you need to get only the date part of it and ignore the time part.

Laravel ^5.6 - Query Scopes
For readability purposes i use query scope, makes my code more declarative.
scope query
namespace App\Models;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
// ...
/**
* Scope a query to only include today's entries.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCreatedToday($query)
{
return $query->where('created_at', '>=', Carbon::today());
}
// ...
}
example of usage
MyModel::createdToday()->get()
SQL generated
Sql : select * from "my_models" where "created_at" >= ?
Bindings : ["2019-10-22T00:00:00.000000Z"]

$today = Carbon\Carbon::now()->format('Y-m-d').'%';
->where('created_at', 'like', $today);
Hope it will help you

No need to use Carbon::today because laravel uses function now() instead as a helper function
So to get any records that have been created today you can use the below code:
Model::whereDay('created_at', now()->day)->get();
You need to use whereDate so created_at will be converted to date.

simple solution:
->where('created_at', 'like', date("Y-m-d")."%");

I’ve seen people doing it with raw queries, like this:
$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));
Or without raw queries by datetime, like this:
$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));
Luckily, Laravel Query Builder offers a more Eloquent solution:
$q->whereDate('created_at', '=', date('Y-m-d'));
Or, of course, instead of PHP date() you can use Carbon:
$q->whereDate('created_at', '=', Carbon::today()->toDateString());
It’s not only whereDate. There are three more useful functions to filter out dates:
$q->whereDay('created_at', '=', date('d'));
$q->whereMonth('created_at', '=', date('m'));
$q->whereYear('created_at', '=', date('Y'));

Below code worked for me
$today_start = Carbon::now()->format('Y-m-d 00:00:00');
$today_end = Carbon::now()->format('Y-m-d 23:59:59');
$start_activity = MarketingActivity::whereBetween('created_at', [$today_start, $today_end])
->orderBy('id', 'ASC')->limit(1)->get();

Carbon::today() will return something like this: 2021-08-06T00:00:00.000000Z, so using Model::where('created_at', Carbon::today()) will only return records created at exactly 12:00 am current date.
Use Model::where('created_at', '>=', Carbon::today()) instead

Post::whereDate('created_at', '=', date('Y-m-d'))->get();
It will give you All the posts created today !!!!! if you use time with this you will get posts of that particular time not of today

laravel 8
$VisitorEntryStatusDateCurrent = VisitorEntry::whereDate('created_at', Carbon::today())->get();

$records = User::where('created_at' = CURDATE())->GET());
print($records);

I use laravel9 on 22 Apr 2022
how I get the "today" record is :
I have edit "config/app.php" on the "timezone" (about line 72 ) I have set it to my timezone which is "Asia/Bangkok"
my query code I have is :
$get = User::whereDate("created_at","=",date("Y-m-d",time() ) )->get();
will get the field that created today.
I don't know if this a correct way or it another bad code but as long as it work for me I will be okay.

Related

Rewrite MYSQL query using Laravel query builder

I'm trying to rewrite MYSQL query using Laravel query builder
So this is the query
DB::select("SELECT * FROM accomodation WHERE id NOT IN
(SELECT accomodation_id FROM bookings
WHERE (`checkin` <= '$request->in' AND `checkout` >= '$request->out'));");
And this is what I've done so far
Accommodation::whereNotIN('id', function($q)
{
$q->select('accomodation_id')
->from('bookings')
->where('checkin', '<=', '$request->out')
->where ('checkout', '>=', '$request->in');
})
->get();
The problem is the first query is giving me expected results but the second one isn't
Can someone point out what I'm doing wrong?
I think you type it wrong. Look at the $request->in and $request->out. You may want to flip it. and why you use '$request->in' instead of $request->in. It will parse as string instead of the value
You don't have use. For example php Accommodation::whereNotIN('id', function($q) use ($request) and you need to flip condition with request ;)

how to add conditional where clause in sql

Looking for improved answer
In Laravel, I am using a raw query. My question is how to add where clause depending on variable value
i.e. if $cid is present then the query should be
select * from user where aid=2 and cid=1;
If it is not present
select * from user where aid=2;
Ideally, I can do it like this
if($cid) {
$query = DB::select("select * from user where aid=2 and cid=1");
} else {
$query = DB::select("select * from user where aid=2");
}
Is there any way to do this without the above method?
This can be achieved with conditional clauses.
$users = DB::table('users')
->where('aid', 2)
->when($cid, function ($query) {
$query->where('cid', 1);
})
->get();
Please contextualize your question well, we don't know what kind of condition you are talking about, nor in what sense your question is asked.
normally the comment above would be enough but it is necessary to specify
Here are some examples from the documentation
$users = DB::table('users')
->where('votes', '=', 100)
->where('age', '>', 35)
->get();
$users = DB::table('users')->where('votes', 100)->get();
You may also pass an array of conditions to the where function. Each element of the array should be an array containing the three arguments typically passed to the where method:
$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
I encourage you to read the documentation which is very clear on this subject and to come back to me in case of misunderstanding
here

Getting data between two given dates is returning nothing Eloquent

I am trying to fetch data if the current date and time falls between start time and end time. Here's what I have done:
$coupon = Coupons::where('start_datetime', '>=', Carbon\Carbon::now()->format('Y-m-d h:m:s'))
->where('end_datetime', '<=', Carbon\Carbon::now()->format('Y-m-d h:m:s') )
->paginate(6);
But this query is not returning anything. I tried to change it see its SQL query but it is all good. My start_datetime and end_datetime formats are both dateTime ('0000-00-00 00:00:00') in my db. I also tried using the date('Y-m-d h:m:s') function in PHP but it's also the same result. How can I possibly do it in my query?
Maybe changing conditions can help you:
$coupon = Coupons::where('start_datetime', '<=', Carbon\Carbon::now()->format('Y-m-d h:m:s'))
->where('end_datetime', '>=', Carbon\Carbon::now()->format('Y-m-d h:m:s') )
->paginate(6);
Thanks for the answer guys, I have figured it out. My DB column is using 24hr format and my query is using 12hr format only. So I have just changed Carbon\Carbon::now()->format('Y-m-d h:m:s') to Carbon\Carbon::now()->format('Y-m-d H:m:s')

Want to get result between time range in Laravel

I have some records, i want to get records from them where item is not between given time range, here is my code that i already tried but no success
$other_hour_trade = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->select('finaltrade.*')
->where('finaltrade.user_id', $user_id)
->whereNotBetween('finaltrade.created_at', [DB::raw('exchanges.start_time'), DB::raw("ADDTIME(exchanges.start_time, '01:00:00')")])
->whereNotBetween('finaltrade.created_at', [DB::raw('exchanges.close_time'), DB::raw("SUBTIME(exchanges.close_time, '01:00:00')")])
->get();
'finaltrade.created_at' is a datetime field and
'exchanges.start_time' and 'exchanges.close_time' is a only time field
I have join two tables to get results
I don't know how to make this work directly using whereNotBetween, but since you're already trying to resort to some raw SQL in your current code, why not just use whereRaw instead:
$other_hour_trade = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->select('finaltrade.*')
->where('finaltrade.user_id', $user_id)
->whereRaw("finaltrade.created_at NOT BETWEEN exchanges.start_time AND ADDTIME(exchanges.start_time, '01:00:00')")
->whereRaw("finaltrade.created_at NOT BETWEEN exchanges.close_time AND SUBTIME(exchanges.close_time, '01:00:00')")
->get();

Joomla JFactory query to return results after today's date

I'm trying to retrieve data from my Joomla! database, but I only want to return results after today (future dates). I've been trying the following, but it isn't working:
->select('*')
->from($params->get('table'))
->where('state = 1')
->where('eventdate' > date('Y-m-d'))
->order('eventdate');
What do I need to change?
I found my answer.
->select('*')
->from($params->get('table'))
->where('state = 1')
->where('eventdate >= CURDATE()')
->order('eventdate');