I don't understand what the accessor method is supposed to be doing here. What model is this defined on; and why would a single instance of the model calculate the sum from all records?
sum the result of records where condition in blade
hello , i have a condition here
'invoices' => Invoice::latest()->when(request('start_date'), function ($q){
$start_date = Carbon::parse(request('start_date'))->toDateTimeString() ?? '';
$end_date = Carbon::parse(request('end_date'))->toDateTimeString() ?? '';
return $q->whereBetween('created_at',[$start_date,$end_date]);
})->paginate(10),
Edit I do not want to repeat the query again to sum where type 1 and the coming result is correct and i need to sum amount invoice where type = 1 so i have created this method inside model
public function getTotalRevenuesAttribute()
{
return $this->whereType('1')->sum('amount');
}
and work correctly - but when i use the date filter and get 1 or 2 rows or any count the total revenues still static i mean the method sum the revenues for all table regardless of records coming from invoices - and i use the if condition
@if($invoice->type == 1)
{{$invoics->sum('amount')}}
@endif
and still sum all records !
The solution i found for now - is use latest() with get()
return view('admin.invoices.index',[
'invoices' => Invoice::latest()->when(request('start_date'), function ($q){
$start_date = Carbon::parse(request('start_date'))->toDateTimeString() ?? '';
$end_date = Carbon::parse(request('end_date'))->toDateTimeString() ?? '';
return $q->whereBetween('created_at',[$start_date,$end_date]);
})->get()->paginate(10),
]);
to decrease the quires and in blade
{{$invoices->where("type", 2)->sum('amount')}}
so here from 11 quire to 1 quires :D
Please or to participate in this conversation.