Laravel - where less/greater than date syntax - php

This is not showing the correct count. What is the correct syntax ?
$this->data['Tasks'] = \DB::table('tb_tasks')->where('Status', 'like', 'Open%')->whereDate('DeadLine', '>', 'CURDATE()')->count();

Use a Carbon instance:
$this->data['Tasks'] = \DB::table('tb_tasks')->where('Status', 'like', 'Open%')->whereDate('DeadLine', '>', Carbon::now())->count();
You can also use the now() helper
$this->data['Tasks'] = \DB::table('tb_tasks')->where('Status', 'like', 'Open%')->whereDate('DeadLine', '>', now())->count();

Use DB::raw:
->where('datefield', '>', \DB::raw('NOW()'))

We can also try this one. It works for me.
$date = "2020-04-10";
/*
Assumimng DB `login_date` datetime format is "Y-m-d H:i:s"
*/
$from_date = $date.' 00:00:01';
->where('login_date', '>=', $from_date);
By adding Where Clause in the query, we can find the result having
rows after the particular date.
Option-2:
$date = "2020-03-25"; // Format: date('Y-m-d);
$orders = DB::table('orders')
->select('*')
->whereDate('order_datetime', '<=', $date)
->get();
// Here, Table Field "order_datetime", type is "datetime"
// Assuming DB `order_datetime` stores value format like: "Y-m-d H:i:s"

you can make use of whereDate like below:
$query->whereDate('DeadLine', '>', Carbon::now())->count();

Related

Laravel: where not expired?

I have a column called expires_at and its a datetime in my MySQL database. I need to fetch records where expires_at hasn't been met, how can I do this?
My current query looks like this
Model::where('user_id', Auth::user()->id)->get();
You can also try this.
use Carbon\Carbon;
use App\Model;
$now = Carbon::now();
Model::where('user_id', Auth::user()->id)
->where('expired_at', '>', $now)
->get();
https://laravel.com/docs/5.6/queries#where-clauses
If you're looking to compare with current date, try:
Model::where('user_id', Auth::user()->id)
->whereDate('expired_at', '>', date('Y-m-d H:i:s'))
->get();

Laravel change date format in where clause to match Carbon::now()

I need to select entries based on dates happening in the future and the
entries contain the date format:
12/30/17
I'm trying to format the date and compare to Carbon::now() timestamp, with no luck.
$now = \Carbon\Carbon::now();
$bookings = DB::table('booking')
->select('booking.*')
->where('booking.uid', '=', Auth::id())
->where(DB::raw("(DATE_FORMAT(booking.date,'%Y-%m-%d 00:00:00'))"), ">=", $now)
->get();
You'll need to use STR_TO_DATE to convert the string.
$bookings = DB::table('booking')
->select('booking.*')
->where('booking.uid', '=', Auth::id())
->where(DB::raw("(STR_TO_DATE(booking.date,'%m/%d/%y'))"), ">=", $now)
->get();
STR_TO_DATE will convert 12/30/17 to 2017-12-30
I don't think you really need to check date format. Also, you have some redundand stuff in the query. Just do this:
Booking::where('uid', auth()->id())->where('date', '>=', now())->get();
And if the date format is really different in some of the rows in the same column, you really need to fix this and instead of making some dirty fix for that.
$bookings = DB::table('booking')
->select('booking.*')
->where('booking.uid', '=', Auth::id())
->where(DB::raw("(DATE_FORMAT(booking.date,'%Y-%m-%d'))"), ">=", $now)
->get();

Laravel 4.2: How to convert raw query to Eloquent

I have a raw query which works fine.
$qry ="select date(created_at) as Date,count(id) as Value from performances where date_format(created_at,'%d-%m-%Y') >= '$start_date' and date_format(created_at,'%d-%m-%Y') <= '$to_date' group by Date order by Date desc ";
$stats = DB::select( DB::raw($qry) );
return json_encode($stats);
I would like to convert it in to Eloquent
My controller function is
public function postPerformanceDetails()
{
$start_date = Input::get('start_date');
$to_date = Input::get('to_date');
$start_date = date('Y-m-d',strtotime($start_date));
$to_date = date('Y-m-d',strtotime($to_date));
$stats = Performance::where('created_at', '>=', $start_date)
->where('created_at','<=',$to_date)
->groupBy('perf_date')
->orderBy('perf_date', 'DESC')
->remember(60)
->get([
DB::raw('Date(created_at) as perf_date'),
DB::raw('COUNT(id) as perf_count')
])
->toJSON();
return $stats
}
The raw query works fine but eloquent does not work according to the date input.
I input data in this format 09-03-2015
in database the format is 2015-03-09
If we give 2015-03-09 as start_date and to_date it returns empty string.
Is there any problem with formats?
How can i solve this issue?
The easiest way would be to convert the date in PHP to the database format.
$start_date = date('Y-m-d', strtotime($start_date));
This should lead to your database format: 2015-03-09.
I got the answer as #sleepless suggested.
This is the code.
public function postPerformanceDetails()
{
$event = Input::get('events');
$start_date = Input::get('start_date');
$to_date = Input::get('to_date');
$start_date = date('Y-m-d H:i:s',strtotime($start_date.'00:00:00'));
$to_date = date('Y-m-d H:i:s',strtotime($to_date.'23:59:59'));
$stats = Performance::where('created_at', '>=', $start_date)
->where('created_at','<=',$to_date)
->groupBy('perf_date')
->orderBy('perf_date', 'DESC')
->remember(60)
->get([
DB::raw('Date(created_at) as perf_date'),
DB::raw('COUNT(id) as perf_count')
])
->toJSON();
return $stats;
}

Laravel eloquent get model on date

I want to get all users created on a specified date:
// $date is a Carbon instance parsed from command line argument.
// I checked it and it is correct.
$users = User::where('created_at', '>', $date->startOfDay())
->where('created_at', '<', $date->endOfDay())
->get();
But this returns 0 results, whereas in the database there are rows that correspond to that date.
What am I doing wrong?
Carbon doesn't behave like value object (ie. it's not immutable), so this:
$date->startOfDay();
$date->endOfDay();
simply modifies the $date object and returns it back. That being said, the string that is passed to the query, is obtained when PDO binds it in the prepared statement, when $date is already mutated to endOfDay.
It means that you just pass reference to the object:
$start === $end; // true
So either use different objects:
$users = User::where('created_at', '>', $date->copy()->startOfDay())
->where('created_at', '<', $date->copy()->endOfDay())
->get();
or simply return the string you need in place, instead of the Carbon object:
$users = User::where('created_at', '>', $date->startOfDay()->toDateTimeString())
->where('created_at', '<', $date->endOfDay()->toDateTimeString())
->get();
still, $date will now hold xxxx-xx-xx 23:59:59 timestamp, so keep this in mind in case you need to work with this variable somewhere else.
The problem is not Laravel itself here but Carbon.
When using the following code:
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$start = $date->startOfDay();
$end = $date->endOfDay();
echo $start.' '.$end;
what you get is:
2014-10-07 23:59:59 2014-10-07 23:59:59
so Laravel will execute query:
select * from `users` where `created_at` >'2014-10-07 23:59:59' and `created_at` <'2014-10-07 23:59:59';
and obviously you will get no results.
As you see $start result is not what you expect here.
to make it work the solution I found is creating 2 carbon objects:
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$date2 = new Carbon('2014-10-07');
$start = $date->startOfDay();
$end = $date2->endOfDay();
echo $start.' '.$end;
Now result is as expected:
2014-10-07 00:00:00 2014-10-07 23:59:59
Now you can use:
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$date2 = new Carbon('2014-10-07');
$users = User::where('created_at', '>', $date->startOfDay())
->where('created_at', '<', $date2->endOfDay())
->get();
or
use Carbon\Carbon;
$date = new Carbon('2014-10-07');
$date2 = new Carbon('2014-10-07');
$users = User::whereBetween('created_at', [$date->startOfDay(), $date2->endOfDay()])->get();
In your query lefts the table name:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
Look: http://laravel.com/docs/4.2/queries#selects

Laravel 4 Eloquent Query

I am trying to query the 'created_at' field by the date for today:
$today = DATE('Y-m-d');
$logs = DB::table('bglogs')->where('DATE('created_at')','=',$today)->where('user_id','=',Auth::user()->id)->get();
It tells me that DATE('created_at') is an unknown column? Any suggestions, relatively new to Eloquent so I am sure I've missed something obvious.
Thanks in advance!
EDIT: 6/10/2014
Wanted to note that I had to tweak it a bit as it was bringing back all records rather than a specific date. Not sure why. I finally got this working correctly. Thanks again to all who answered and I hope this update will help others in the future:
$logs = DB::select(DB::raw("SELECT * FROM bglogs WHERE DATE(created_at) = :today AND user_id = :user"), array('today'=>DATE('Y-m-d'), 'user'=>Auth::user()->id));
If you want to use mysql functions you must use whereRaw and wite it in a single string.
In the other where, you can skip the second parameter if it will be equals (=).
$today = DATE('Y-m-d');
$logs = DB::table('bglogs')
->select(DB::raw('*'))
->whereRaw("DATE('created_at') = " . $today)
->where('user_id', Auth::user()->id)
->get();
Hope its help you.
I recommend you dont declare alias if you will use the var just one time:
$logs = DB::table('bglogs')
->select(DB::raw('*'))
->whereRaw("DATE('created_at') = " . DATE('Y-m-d'))
->where('user_id', Auth::user()->id)
->get();
You may try this (Carbon is available with Laravel):
$today = Carbon\Carbon::toDay()->toDateTimeString();
$logs = DB::table('bglogs')->where('created_at', $today)
->where('user_id', Auth::user()->id)
->get();
there is no need to use raw method when you can just define search criteria.
try this:
$today = DATE('Y-m-d');
$logs = DB::table('bglogs')
->where('created_at', '=>', $today.' 00:00:00')
->where('created_at', '<=', $today.' 23:59:59')
->where('user_id', '=', Auth::user()->id)
->get();
if problem still exists so check your table for existence of this created_at field.
$today=date("Y-m-d");
$coustomers=Coustomer::where('created_at','like',"$today%")->get();
You can use Carbon class provided by laravel:
$today = Carbon::today();
$logs = DB::table('bglogs')
->where('created_at','>=',$today)
->where('user_id','=',Auth::user()->id)
->get();
Or
You can use php date functions to do this manually:
$today = new \DateTime(date('F jS Y h:i:s A', strtotime('today')));
$logs = DB::table('bglogs')
->where('created_at','>=',$today)
->where('user_id','=',Auth::user()->id)
->get();

Categories