I am trying to get two date calculation . when i placed
$from = Carbon::createFromFormat('m-d-Y H:i:s', '02-10-2017 10:02:20');
code i get value but when i placed data from mysql
$from = Carbon::createFromFormat('m-d-Y H:i:s', $from_date);
can not find data, and can not calculation to and from date
Controller.php
public function circulerMatchView()
{
$user_id = Auth::user()->id;
$resume_exp = Experience::select('user_exp_keyword')
->where('user_id','=',$user_id)
->get();
$from_date = Experience::selectRaw('exp_from_date')
->where('user_id','=',$user_id)
->orderBy('exp_from_date','desc')
->take(1)
->get();
$to_date = Experience::selectRaw('exp_to_date')
->where('user_id','=',$user_id)
->orderBy('exp_from_date','desc')
->take(1)
->get();
$from = DateTime::createFromFormat('m-d-Y H:i:s', $from_date);
$to = Carbon::createFromFormat('m-d-Y H:i:s', $to_date);
$realAge = Carbon::parse($to)->diff(Carbon::parse($from))->format('%y');
print_r($realAge);
}
if $from_date is 02-21-2017 and $to_date is 02-21-2018
result is 1 year
You are fetching array by using get. Replace these two lines with your codes and check. It will fetch only field data values.
$from_date = Experience::
where('user_id','=',$user_id)
->orderBy('exp_from_date','desc')
->take(1)
->pluck('exp_from_date')[0];
$to_date = Experience::
where('user_id','=',$user_id)
->orderBy('exp_to_date','desc')
->take(1)
->pluck('exp_to_date')[0];
Once check this documentation for details about pluck.
Related
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();
I'm trying to create a report page that shows reports from a specific date to a specific date. Here's my current code:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', $now)->get();
What this does in plain SQL is select * from table where reservation_from = $now.
I have this query here but I don't know how to convert it to eloquent query.
SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to
How can I convert the code above to eloquent query?
The whereBetween method verifies that a column's value is between
two values.
$from = date('2018-01-01');
$to = date('2018-05-02');
Reservation::whereBetween('reservation_from', [$from, $to])->get();
In some cases you need to add date range dynamically. Based on #Anovative's comment you can do this:
Reservation::all()->filter(function($item) {
if (Carbon::now()->between($item->from, $item->to)) {
return $item;
}
});
If you would like to add more condition then you can use orWhereBetween. If you would like to exclude a date interval then you can use whereNotBetween .
Reservation::whereBetween('reservation_from', [$from1, $to1])
->orWhereBetween('reservation_to', [$from2, $to2])
->whereNotBetween('reservation_to', [$from3, $to3])
->get();
Other useful where clauses: whereIn, whereNotIn, whereNull, whereNotNull, whereDate, whereMonth, whereDay, whereYear, whereTime, whereColumn , whereExists, whereRaw.
Laravel docs about Where Clauses.
And I have created the model scope
To Know More about scopes check out the below links:
laravel.com/docs/eloquent#query-scopes
medium.com/#janaksan/using-scope-with-laravel
Code:
/**
* Scope a query to only include the last n days records
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhereDateBetween($query,$fieldName,$fromDate,$todate)
{
return $query->whereDate($fieldName,'>=',$fromDate)->whereDate($fieldName,'<=',$todate);
}
And in the controller, add the Carbon Library to top
use Carbon\Carbon;
To get the last 10 days record from now
$lastTenDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(10)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->get();
To get the last 30 days record from now
$lastThirtyDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(30)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->get();
Another option if your field is datetime instead of date (although it works for both cases):
$fromDate = "2016-10-01";
$toDate = "2016-10-31";
$reservations = Reservation::whereRaw(
"(reservation_from >= ? AND reservation_from <= ?)",
[
$fromDate ." 00:00:00",
$toDate ." 23:59:59"
]
)->get();
If you want to check if current date exist in between two dates in db:
=>here the query will get the application list if employe's application from and to date is exist in todays date.
$list= (new LeaveApplication())
->whereDate('from','<=', $today)
->whereDate('to','>=', $today)
->get();
The following should work:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
->where('reservation_from', '<=', $to)
->get();
If you need to have in when a datetime field should be like this.
return $this->getModel()->whereBetween('created_at', [$dateStart." 00:00:00",$dateEnd." 23:59:59"])->get();
Try this:
Since you are fetching based on a single column value you can simplify your query likewise:
$reservations = Reservation::whereBetween('reservation_from', array($from, $to))->get();
Retrieve based on condition: laravel docs
Hope this helped.
I followed the valuable solutions provided by other contributors and faced a minor issue no one has addressed. If the reservation_from is a datetime column then it might not produce results as expected and will miss all the records in which the date is same but time is anything above 00:00:00 time. To improve the above code a bit a small tweak is needed like so.
$from = Carbon::parse();
$to = Carbon::parse();
$from = Carbon::parse('2018-01-01')->toDateTimeString();
//Include all the results that fall in $to date as well
$to = Carbon::parse('2018-05-02')
->addHours(23)
->addMinutes(59)
->addSeconds(59)
->toDateTimeString();
//Or $to can also be like so
$to = Carbon::parse('2018-05-02')
->addHours(24)
->toDateTimeString();
Reservation::whereBetween('reservation_from', [$from, $to])->get();
I know this might be an old question but I just found myself in a situation where I had to implement this feature in a Laravel 5.7 app. Below is what worked from me.
$articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();
You will also need to use Carbon
use Carbon\Carbon;
Here's my answer is working thank you Artisan Bay i read your comment to use wheredate()
It Worked
public function filterwallet($id,$start_date,$end_date){
$fetch = DB::table('tbl_wallet_transactions')
->whereDate('date_transaction', '>=', $start_date)
->whereDate('date_transaction', '<=', $end_date)
->get();
the trick is to change it :
Reservation::whereBetween('reservation_from', [$from, $to])->get();
to
Reservation::whereBetween('reservation_from', ["$from", "$to"])->get();
because the date must be in string type in mysql
#masoud , in Laravel, you have to request the field value from form.So,
Reservation::whereBetween('reservation_from',[$request->from,$request->to])->get();
And in livewire, a slight change-
Reservation::whereBetween('reservation_from',[$this->from,$this->to])->get();
you can use DB::raw('') to make the column as date MySQL with using whereBetween function as :
Reservation::whereBetween(DB::raw('DATE(`reservation_from`)'),
[$request->from,$request->to])->get();
Another way:
use Illuminate\Support\Facades\DB;
$trans_from = date('2022-10-08');
$trans_to = date('2022-10-12');
$filter_transactions = DB::table('table_name_here')->whereBetween('created_at', [$trans_from, $trans_to])->get();
Let me add proper syntax with the exact timestamp
Before
$from = $request->from;
$to = $request->to;
Reservation::whereBetween('reservation_from', [$from, $to])->get();
After
$from = date('Y-m-d', strtotime($request->from));
$to = date('Y-m-d', strtotime($request->to));
Reservation::whereBetween('reservation_from', [$from, $to])->get();
Note: if you stored date in string form, then make sure to pass the exact format in from and to. Which will be matched with DB.
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;
}
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
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();