return redirect->back() inside DB::transaction()

3837 views php
-3

I was trying to execute some statement inside DB::transaction method but the problem when a certain condition failed it should return redirect()->back()

But the problem is code neither redirect back nor getting executed further. What could be the possible reason for that?

  return DB::transaction(function ()  use ($request){ 
            $sellerItem = new SellerItem();
            $sellerItem->item_id = $request->item_id;
            $sellerItem->unit_price = $request->unit_price;
            $sellerItem->quantity = $request->quantity;
            $sellerItem->paid_amount = $request->paid_amount; 

            $sellerItem->payment_method = $request->payment_method;
            $sellerItem->seller_id = $request->seller_id;

            $sellerItem->due = ($request->unit_price*$request->quantity) + $request->due - $sellerItem->paid_amount; 
        //   dd($sellerItem);
            $sellerItem->before_due = $request->due;
 **Problem is in this block of statement**
            if($sellerItem->due<0)
            {

            return redirect()->back()->with('success', "Paid amount can't be greater than ".abs(($request->unit_price*$request->quantity) + $request->due)); 
            }

            $sellerItem->save();
            $item = Item::find($request->item_id);
            $item->quantity = $item->quantity+$request->quantity;
            $item->save();

            return redirect('item/stock-in');

              });

answered question
Sagar Gautam

You can't add such redirect inside call back function, use custom transaction

Add a Comment

1 Answer

2
atymic 0 Comments

One way to solve this would be to use the Facade rather than the closure.

For example, with your code:

DB::beginTransaction();

$sellerItem = new SellerItem();
$sellerItem->item_id = $request->item_id;
$sellerItem->unit_price = $request->unit_price;
$sellerItem->quantity = $request->quantity;
$sellerItem->paid_amount = $request->paid_amount;

$sellerItem->payment_method = $request->payment_method;
$sellerItem->seller_id = $request->seller_id;

$sellerItem->due = ($request->unit_price * $request->quantity) + $request->due - $sellerItem->paid_amount;
$sellerItem->before_due = $request->due;
if ($sellerItem->due < 0) {
    DB::rollBack();
    return redirect()->back()->with('success',
        "Paid amount can't be greater than " . abs(($request->unit_price * $request->quantity) + $request->due));
}

$sellerItem->save();
$item = Item::find($request->item_id);
$item->quantity = $item->quantity + $request->quantity;
$item->save();

DB::commit();
return redirect('item/stock-in');

posted this

Please login first before posting an answer.