phplaravel-5eloquentlaravel-5.3illuminate-container

Does Laravel 5.3019 database Transaction method work?


I've use Larvel 5.0 with Database transaction all the method in my previous web application it work as well and we are really love it because this application help me much more than our estimated

so we have create another webs application by using this newest version of this framework and used the same Database structure but finaly it would not work for me and another one to. I have as more peoples and post on some toturial website for asking any belp but not yet get any solution so I record this video for sure about this case.

Issue: My issue I've disabled (//commit()) method all data still can insert into Database.

 final function Add()
    {
        if ($this->request->isMethod('post')) {

            //No you will see this method use with Try Catch and testing again
            //DB::beginTransaction(); // Ihave testing with outside of try and inside again

            Try{

                DB::beginTransaction();

                $cats = new Cat();
                $catD = new CategoryDescriptions();

                $cats->parent_id = $this->request->input('category_id');
                $cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
                if (($res['result'] = $cats->save())== true) {

                    $catD->category_id = $cats->id;
                    $catD->language_id = 1;
                    $catD->name = $this->request->input('en_name');
                    if (($res['result'] = $catD->save()) === true) {

                        $catD2 = new CategoryDescriptions();
                        $catD2->category_id = $cats->id;
                        $catD2->language_id = 2;
                        $catD2->name = $this->request->input('kh_name');
                        $res['result'] = $catD2->save();
                    }
                }
                if(!empty($res)) {
                    //DB::commit();
                }
                return [$res,($res['result'] = $catD->save())];
            }catch(\Exception $e){ // I have already try to use Exception $e without backslash
                DB::rollback();
            }
        }

        $cat = Cat::with(['CategoryDescriptions', 'children'])->where('status', 1)->get();

        return view('admin.categories.add', ['cat' => $cat]);
    }

You can check on my video to see that .

Check on my video


Solution

  • I don't know why your code did not work. But you can try with this code I think it's will work. Laravel transaction documentation

    try{
         DB::transaction(function)use(/*your variables*/){
    
           // your code
       });
     }catch(\PDOException $exception){
        //debug
    }
    

    If any exception occurs it will automatically rollback. If you want manual rollback then inside transaction you can throw a manual exception based on your logic.