I have a column in my table called date which is of type TIMESTAMP.
I am trying to add a very simply scope which will return all results that have a date of tomorrow.
I think I want to be able to do something like this:
public function scopeTomorrow($query)
{
return $query->where('date', function ($date) {
return \Carbon\Carbon::parse($date)->isTomorrow();
});
}
But the $date variable is currently just the query builder.
How can I create a where statement which accepts the value and perfroms some sort of check on it?
You can do this:
return $query->where('date', '>=', Carbon::tomorrow())
->where('date', '<=', Carbon::tomorrow()->endOfDay());
Or:
return $query->whereBetween('date', [Carbon::tomorrow(), Carbon::tomorrow()->endOfDay()]);
Also, probably you want to add date to $dates variable.
You can do something like this:
public function scopeTomorrow($query)
{
$tomorrow = \Carbon\Carbon::now()->addDay(1);
return $query->where('date', '=', $tomorrow);
}
Related
my code in LaporanController.php
class LaporanController extends Controller
{
public function index(Request $request)
{
if (isset($request->start_date) && isset($request->end_date)) {
$start_date = Carbon::parse($request->start_date)->format('Y-m-d');
$end_date = Carbon::parse($request->end_date)->format('Y-m-d');
$attendance_absent = DB::table('attendance_absent as absent')
->whereBetween('absent.do_date_start', 'absent.do_date_end', [$start_date, $end_date])
->get();
dd($attendance_absent);
}
}
}
how to get request data from start_date and end_date according to attendance_absent table from database fields do_date_start and do_date_end? i try to use whereBetween but i get error : Illuminate\Database\Query\Builder::whereBetween(): Argument #2 ($values) must be of type array, string given. how to solve my problem ?
normally whereBetween using for single column date check. but in this case youu need get from the different columns. so try to check those date like this. i think it will we help full for you.
do try it like this
->whereDate('do_date_start', '>=', $from_date)
->whereDate('do_date_start', '<=', $to_date)
->whereDate('do_date_end', '>=', $from_date)
->whereDate('do_date_end', '<=', $to_date)
other thin if you used whereBetween you will not get equal date of today.
whereBetween function is used to query one field with 2 or more values, what you really want is just where function twice, try this:
...
->where([
['absent.do_date_start', '>=', $start_date],
['absent.do_date_end', '<=', $end_date],
])
->orWhere(function ($query) use ($start_date, $end_date) {
$query->where([
['absent.do_date_start', '>', $start_date],
['absent.do_date_start', '>', $end_date],
['absent.do_date_end', '<', $start_date],
['absent.do_date_end', '<', $end_date],
])
})
->get();
...
Are there any way to get difference of two days (today & created_at) using laravel query?
I have tried as follows.but that didn't work for me
public function scopeActivatedOrders($query,$currentDate){
return $query->select('*')
->where('orders.activated', '=', '1')
->where('DATEDIFF(order.arrived_date,$currentDate)','>','14')->get();
}
Thank you!
the problem in your code is that you are using standard where that take a column as the first parameter not an expression ...
you can use whereRaw, or just using DB::raw like:
return $query->select('*')
->where('orders.activated', '=', '1')
->whereRaw('DATEDIFF(order.arrived_date,Now())>14')->get();
note: you can mysql now() function instead of $currentDate variable ...
try this 1st select then add in where condition
public function scopeActivatedOrders($query, $currentDate)
{
return $query->select('orders.*', \DB::raw('DATEDIFF(order.arrived_date, NOW()) as diffday'))
->where('orders.activated', '=', '1')
->get()
->where('diffday', '>', '14');
}
Can you give an idea?
I have two tables in to postgresql DB.
The are filled with recods by two separate csv files. But the records of the first csv file are with local timestamp. The second csv file is with timestamps UTC.
So I need to change the time in local of the view in this table that is filled with records with timezone UTC. I used to deal with that problem before using laravel with this code in every page that I need to do that, for example:
date_default_timezone_set('Europe/Sofia');
The controller:
function getdata_chart(Request $request)
{
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
Update your Model MeasCanal and add the following :
Import and use :
use Carbon\Carbon;
Add Function :
/**
* Get the user's recordtime.
*
* #param string $value
* #return string
*/
public function getRecordtimeAttribute($value)
{
return Carbon::parse($value)->timezone('Europe/Sofia')->toDateTimeString();
}
I'm not sure this is what you want but i think you can get the idea.
First Method,
You can use accessor;
public function getCustomTimestampAttribute($value)
{
// you can use your logic here to set your timezone by table
$timezone = 'Europe/Sofia';
return Carbon::parse($this->custom_timestamp)->timezone($timezone)->toDateTimeString();
}
then you can get the value like: $model->custom_timestamp
Second Method,
You can use map;
$customDates = $dates->map(function ($date, $key) {
$date->custom_timestamp = Carbon::parse($date->custom_timestamp)->timezone('Europe/Sofia')->toDateTimeString();
return $date;
});
EDIT
In your model(MeasCanal) set recordtime attribute;
public function getRecordtimeAttribute($value)
{
// you can use your logic here to set your timezone by table
$timezone = 'Europe/Sofia';
return Carbon::parse($this->recordtime)->timezone($timezone)->toDateTimeString();
}
then you can simply see the result after the query in your controller like
dd($students);
or even simpler to see:
dd($students->first()->recordtime); // first matched rows recordtime attr.
Note: you cant use accessors with raw queries you should use eloquent models btw.
I have this code
use Carbon;
$now = Carbon::now()->toDateString();
So i get the date without the time
public funtion test($brandid){
$nbofsale=DB::table('st_nsales')
->where('brand_id', $brandid)
->where('eodate', $now)
->get();
return $nbofsale;
}
The eodate field in the select is datetime. I want to put it in this query as date only and not to change the field type in database.
Any ideas?
If eodate is a timestamp, you don't need to convert it to a date string:
$nbofsale = DB::table('st_nsales')
->where('brand_id', $brandid)
->whereDate('eodata', Carbon::today()->toDateString());
->get();
Another way to get record for today:
$nbofsale = DB::table('st_nsales')
->where('brand_id', $brandid)
->where('eodata', '>', Carbon::now()->startOfDay());
->get();
I have a query the uses many ->with() in Laravel like so:
$campaign = $this->campaign
->with('tracks.flights.asset')->take(4)
->with('tracks.group')
->with('tracks.media')
->with('tracks.flights.comments')
->orderBy('created_at', 'desc')->find($id);
and in the Track model i have this method:
public function flights()
{
return $this->hasMany('Flight\Flight')->orderBy('start_date');
}
What I want to achieve is having the same result as now but i want to put date constrains on the flight level, for example something like this:
public function flights($start_date, $end_date) //dynamic dates
{
return $this->hasMany('Flight\Flight')->whereRaw('start_date > $start_date and end_date < $end_date')->orderBy('start_date');
}
How can I achieve this kind of result? I am fairly new to Laravel.
Thanks in advance.
Chain a whereHas onto your query.
$campaign = $this->campaign
->with('tracks.flights.asset')->take(4)
->with('tracks.group')
->with('tracks.media')
->with('tracks.flights.comments')
->whereHas('tracks.flights', function($q) use ($start_date, $end_date) {
$q->where('start_date', '>', $start_date)->where('end_date', '<', $end_date)->orderBy('start_date');
})
->orderBy('created_at', 'desc')->find($id);
Keep in mind the orderBy will only order the results returned within the flights relation, not the campaigns themselves.
This is the solution i came up with after reading Eloquent ORM in Laravel
$campaign = $this->campaign
->with(array('tracks.flights' => function($query)
{
$query->whereRaw('flights.start_date > "2016-01-09 00:00" AND flights.end_date < "2016-01-16 00:00"')
->with('asset')->take(4)
->with('comments');
}
))
->with('tracks.group')
->with('tracks.media')
->orderBy('created_at', 'desc')->find($id);