I have this $query Function in my Controller. It works. But when i try to add a variable inside it, it's not working.
this is my Full function
$setting = DB::table('settings')->where('id','=','1')->get();
foreach($setting as $st)
$date1 = $st->date1;
$date2 = $st ->date2;
$accounts = Account::with(['subaccount' => function($query){
$query->with(['subaccountinvoice'=> function($query){
$query->where('validate', '=','1')->whereBetween('updated_at', [$date1, $date2]);}])->get();
}])->get();
Variables $date1 and $date2 are not defined because they are insidd Query Function
In order to inherit a variable within a closure in PHP you need to pass it to the closure using the use keyword.
Change your accounts code to this:
$accounts = Account::with(['subaccount' => function($query) use ($date1, $date2) {
$query->with(['subaccountinvoice'=> function($query) use ($date1, $date2) {
$query->where('validate', '=','1')->whereBetween('updated_at', [$date1, $date2]);}])->get();
}])->get();
Related
I need to format the date to search, since the date that comes from the variable is the example 2021-09-03, without the time and the one from the database comes with the time. I only need to look for the date, not the time.
SaleController.php
public function index()
{
$idUser = Auth::id();
$search = request('calendar');
$sale = Sale::with('client', 'products')->where('user_id', '=', $idUser)->where("DATE_FORMAT(updated_at, '%Y-%m-%d')", '=', $search)->get();
//Here it throws an error because it is misspelled
return $sale;
}
I only need to look for the date, not the time.
You could do this when filtering for date ranges:
$start_date = $request->start_date;
$end_date = $request->end_date;
$sale = Sale::whereBetween('created_at', [$start_date, $end_date])->with('client', 'products')->where('user_id', '=', $idUser)->get()
or this as in your own use case
$search = request('calendar');
$sale = Sale::where('created_at', $search )->with('client', 'products')->where('user_id', '=', $idUser)->first();
To reduce the amount of data loaded for each query, you could refactor your query to:
$search = request('calendar');
$sale = Sale::where('user_id', '=', $idUser)->with('client', 'products')->where('created_at', $search )->first();
Note the use of "first()" instead of "get()" first() returns an object while get() returns an array.
You can use the whereRaw query builder method for raw SQL expressions:
$sale = Sale::with('client', 'products')->where('user_id', '=', $idUser)->whereRaw("DATE_FORMAT(sales.updated_at, '%Y-%m-%d') = '?'", [$search])->get();
See: https://laravel.com/docs/8.x/queries#whereraw-orwhereraw
I want some help with a WHERE clause $start date is set further up in the code, and the query works when running against SQL from within Laravel. I get an error saying that $startdate isn't set. I am not sure that I am even doing WHERE correctly.
$query = DB::query()
->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
->fromSub
(function (\Illuminate\Database\Query\Builder $query) {
$query->select('user_id', DB::raw('count(user_id) AS CC '))
->from('mytable')
->where('created_at', '>=', $startdate)
->groupBy('user_id');
}, 'CC')
->groupBy('CC');
$result = DB::connection('mysql2')->select($query->toSql());
I'm putting this here for others who find this page. It should be noted that fromSub() can also take a Builder object instead of a closure.
$builder = DB::table('mytable')->where('created_at', '>=', $start_date)
->select('user_id', DB::raw('count(user_id) AS CC '))
->groupBy('user_id');
$query = DB::query()
->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
->fromSub($builder, 'temp')
->groupBy('CC');
In my case, I already had a Builder object that I wanted to use in a sub select.
That's because your fromSub is an anonymous function, also known as a closures. It does not know about variables that you define outside of the closure. You can read more about them in the official PHP docs
Rewrite your query to:
$result = DB::connection('mysql2')
->query()
->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
->fromSub(function($query) use ($startdate) {
$query->select('user_id', DB::raw('count(user_id) AS CC '))
->from('mytable')
->where('created_at','>=',$startdate)
->groupBy('user_id');
}, 'temp')
->groupBy('CC')
->get();
I want to write a class to submit using the function method and get access to example_method at the class
$users = User::where('posts', function($q){
$q->example_method ('created_at', '>=', '2015-01-01 00:00:00');
})->get() ;
As I understand - you want to have access to $q variable in anonymous function, you can access it this way:
$users = User::where('posts', function() use ($q) {
$q->example_method ('created_at', '>=', '2015-01-01 00:00:00');
})->get() ;
In case you want access variable defined outside function you have to inherit it using use.
More info: https://www.php.net/manual/en/functions.anonymous.php
I have the following tables (with only relevant fields):
devices
id
name
created_at
updated_at
device_reports
id
device_id
location
created_at
updated_at
I have a report with a number of filters on it that is already working, so I want to stick with the eloquent way of doing things. Here is Controller function:
public function devices(Request $request)
{
$devicesQuery = Device::with(['latestReport']);
if ($request->ajax())
{
if($request->input('start') && $request->input('start')!='')
{
$start_date = date('Y-m-d', strtotime($request->input('start')));
$end_date = date('Y-m-d', strtotime($request->input('end')));
$devicesQuery = $devicesQuery->lastReportBetween($start_date,$end_date);
}
$devices = $devicesQuery->paginate(10);
return Response::json(View::make('devices/table', array('devices' => $devices))->render());
}
}
The model's latestReport is defined as:
public function latestReport()
{
return $this->hasOne('App\Models\DeviceReport')->latest();
}
The model's function lastReportBetween is defined as:
public function scopeLastReportBetween($query, $start, $end)
{
$query = $query->join('device_reports AS dr', 'dr.device_id', '=', 'devices.id');
$query = $query->where('dr.id', '=', DB::raw('(SELECT max(dr2.id) FROM device_reports AS dr2 WHERE dr2.device_id = devices.id)'));
$query = $query->where(DB::raw("(IFNULL(dr.gps_time, dr.created_at))"), '>=', DB::raw("STR_TO_DATE('".$start."', '%Y-%m-%d')"));
$query = $query->where(DB::raw("(IFNULL(dr.gps_time, dr.created_at))"), '<=', DB::raw("STR_TO_DATE('".$end."', '%Y-%m-%d')"));
return $query;
}
When running the above with a start/end date selected, I get the correct records returned, but I don't get anything returned in "latestReport", but when I run the page without the date filters in place, it correctly returns the device information and the most recent report record in the latestReport class variable.
Can anyone help me understand how to change this code such that I do get the latestReport back when I also call the lastReportBetween function?
I figured out my problem. I should have been using "whereHas()" instead of manual joins and whatnot.
public function scopeLastReportBetween($query, $start, $end)
{
return $query->whereHas('latestReport', function($reportsQuery) use ($start, $end)
{
$reportsQuery->whereBetween('created_at', [$start, $end])
->where('device_reports.id', '=', DB::raw('(SELECT max(dr2.id) FROM device_reports AS dr2 WHERE dr2.device_id = device_reports.device_id)'));
});
}
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);
}