Laravel: Divide into monthly installments

I think you need something like this:

public function store(RegisterAccountsRequest $request){
    if($request->installment > 1){
        $dueDate = Carbon::createFromFormat('d/m/Y', $request->due_date);
        foreach(range(1, $request->installment) as $installment) {
            $data = new Financial;
            $data->type = $request->type[0];
            $data->payment = $request->payment[0];
            $data->description = $request->description;
            $data->status = $request->status;
            $data->name = $request->name . " ( {$installment} / {$request->installment} )";
            $data->value = ( $request->value / $request->installment );
            if ($request->amount_paid == '0.00') {
                $data->effective = 0;
            } else {
                $data->effective = 1;
            }
            $data->installment = $installment;
            $data->due_date = $dueDate->format('d/m/Y');
            $dueDate->addMonth();
            $data->save();

            $cf = new ClientFinancial;
            $cf->client_id = Auth::user()->id;
            $cf->financial_id = Financial::orderBy('id', 'desc')->first()->id;
            $cf->save();
        }
    } else {
        $data = new Financial;
        $data->type = $request->type[0];
        $data->payment = $request->payment[0];
        $data->description = $request->description;
        $data->status = $request->status;
        $data->name = $request->name;
        $data->value = $request->value;
        if ($request->amount_paid == '0.00') {
            $data->effective = 0;
        } else {
            $data->effective = 1;
        }
        $data->installment = 1;
        $data->due_date = $request->due_date;
        $data->save();

        $cf = new ClientFinancial;
        $cf->client_id = Auth::user()->id;
        $cf->financial_id = Financial::orderBy('id', 'desc')->first()->id;
        $cf->save();
    }

    return redirect()->route('admin.financials.index')
        ->with('success', "Conta cadastrada com sucesso!", $data);
}

In this case I make a Carbon(carbon docs) instance with date due_date. After using the value like so $data->due_date = $dueDate->format('d/m/Y'); and then adding one month like so $dueDate->addMonth(); I have a new month available each iteration.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top