I am trying to learn to improve my coding on a daily basis and this is one of the first times I am posting on here, so bear with me.
I have two models, a Payment and an Expense model. A payment
hasMany expenses
. In a table I am showing all payments, including the sum of all expenses for each payment. Now I would like to update the data based on a URL parameter type
. A payment
can have a type of contract
, subscription
or payment_plan
.
In my controller I am doing the following to achieve this:
public function index(Request $request)
{
$type = $request->input('type') ?? null;
$query = auth()->user()->payments()->where('status', 'active'); // Only query active payments
if ($type !== null)
{
$query->where('type', $type);
}
$count = $query->count(); // The total count of active payments
$amount = $query->sum('amount'); // The total amount of all active payments
$paid = $query->withSum('expenses', 'amount')->get(); // Getting all related expenses for each payment, including the sum of the amount of all those expenses
$paid = $paid->sum('expenses_sum_amount'); // Getting the total sum
$remaining = $amount - $paid; // The remaining amount that has to be paid
return view('payments.index')
->withPaymentNumber($count)
->withPaymentAmount($amount)
->withPaymentPaid($paid)
->withPaymentRemaining($remaining);
}
I know this code can be improved alot upon, and I would love to see other people's visions on how they would achieve this.