D
D
DenKG2016-12-05 06:51:10
Laravel
DenKG, 2016-12-05 06:51:10

Why does Call to a member function decrement() on null crash?

It is necessary for me from the available sum in a DB to take away entered in the form.
Here is my controller:

$transactions = new Transaction;

   $transactions->trans_pay_sum = $request->trans_pay_sum;
   $transactions->trans_pay_appoint = $request->trans_pay_appoint;
   $transactions->trans_pay_purse_name = $request->trans_pay_purse_name;
   $transactions->trans_pay_purse_client_id = Auth::id();

public function payment(Request $request){
     $purse = Purse::where('purse_name', $request->trans_pay_purse_name)->first();
     $purse->decrement('purse_balance',  $request->trans_pay_sum);
     $purse->save();
     return view('home');
  }

Although an increment with the same code as in payment works great. What is the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad, 2016-12-05
@DenKG

It is likely that the search by name returned null.
To ignore the error or handle it somehow, better check:

$purse = Purse::where('purse_name', $request->trans_pay_purse_name)->first();
if ($purse) {
    $purse->decrement('purse_balance',  $request->trans_pay_sum);
    $purse->save();
} else {
    return redirect()->back()->withInput()->with('error', 'Кошелек не найден!');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question