Why DB::transaction() not work correctly in laravel?

Viewed 744

I am working with Laravel version 7, I want to insert data into two tables, inside_order and inside_order_total. I used transaction to control that data should insert in both, but if there be a problem not insert it in any of them. but transaction does not work correctly. I searched and tried many ways, but my problem was not solved.

This is my code:-

try {
    DB::beginTransaction();
    $request->validate([
        'menu_id' => 'required',
        'order_amount' => 'required',
        'order_price' => 'required',
        'total' => 'required',
        'table_order' => 'required'
    ], [
        'menu_id.required' => 'افزودن مینوی غذایی الزامی است.',
        'order_amount.required' => 'تعداد سفارشات الزامی است.',
        'total.required' => 'مقدار کلی پول باید بیشتر از صفر باشد.',
        'table_order.required' => 'انتخاب میز الزامی است',
        'order_price.required' => 'هیچ مقدار پولی وارد نشده است.',
    ]);

    $total = new InsideOrderTotal();
    $data = $request->all();
    $user = User::all();
    $total->location_id = $data['table_order'];
    $total->total = $data['total'];
    $total->identity = \random_int(100000, 999999);
    Notification::send($user, new newOrderNotification('سفارش جدید دارید!'));
    $total->save();

    foreach ($request->input('menu_id') as $item => $value) {
        $order = new InsideOrder();
        $order->total_id = $total->order_id;
        $order->menu_id = $data['menu_id'][$item];
        $order->order_amount = $data['order_amount'][$item];
        $order->price = $data['order_price'][$item];
        $order->save();
    }
    DB::commit();
    $response = array(
        'status' => 'success',
        'msg' => 'موفقانه انجام شد!',
    );
    return response($response);
} catch (\PDOException $e) {
    DB::rollBack();
    return redirect()->back()->with('errors', 'error');
}

I have tried this:-

DB::transaction(function() {

});

And this:-

DB::connection('tools')->beginTransaction();
DB::connection('tools')->commit();
DB::connection('tools')->rollBack();

But none of them worked. If I change a column name in my database in one table, it inserts in one of them. actually, it should not be like that.

0 Answers
Related