0
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Using eloquent when() function the above code would be cleaner, especially if you add more filters in the future.

I am not sure what version of laravel you are using, but Request injection probably can be replaced by the request() function.

public function index() {
    $query = auth()->user()->payments()
        ->where('status', 'active') // Only query active payments
        ->when(request('type') !== null, function ($query) {
            return $query->where('type', request('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);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.