PamanBeruang
PamanBeruang

Reputation: 1589

Rollback transaction for multiple and connected eloquent

so i am having issue since in my store function on my controller i am doing 2 (or more) create and the second create depends on first create id and when my second create failed it gonna return exception but the first create is already been done and because my first create have an unique validation rules, the next time user hit save button on the front end it will show error because duplicate entry.

it is looks like this in my controller

public function store(Request $request)
{
    try{
        $this->validate($request,Seller::$rules);

        $name = $request->name;

        if(!empty($request->gambar))
            $fileName = Helper::image_processing($this->imagepath,$this->width,$this->height,$request,'');
        else
            $fileName = ''; 

        // my first create
        $class = Seller::create($request->except('gambar') + [
            'gambar' => $fileName
        ]);

        // my second create that depends on first create id
        $this->syncProduct($request, $class->id);

        return response()
            ->json([
                'saved' => true,
                'message' => $this->message. ' ' .$name. ' already been added',
                'id' => $class->id
            ]); 
    } catch (\Exception $e){
        $errorCode = $e->errorInfo[1];
        if($errorCode == 1062){
            abort(500, 'Duplicate seller id');
        }else{
            abort(500, $e->getMessage());
        }
    }
}

my question is how to have some kind of rollback features that if anything gone wrong inside it then it will go back in time to before any data is created/updated?

Upvotes: 0

Views: 392

Answers (1)

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

You can use \DB::beginTransaction() for begin transaction. To commit \DB::commit(); and if you get any error from catch then you may rollback as by this \DB::rollBack();.

// Begin Transaction
\DB::beginTransaction(); 
    try {
       //your code.
       // Commit Transaction
        \DB::commit();

    } catch (\Illuminate\Database\QueryException $ex) {
        $msg = $ex->getMessage();
        if (isset($ex->errorInfo[2])) :
            $msg = $ex->errorInfo[2];
        endif;
        // Rollback Transaction
        \DB::rollBack();
        $arr = array("status" => 400, "msg" =>$msg, "result" => array());
    } catch (Exception $ex) {
        $msg = $ex->getMessage();
        if (isset($ex->errorInfo[2])) :
            $msg = $ex->errorInfo[2];
        endif;
        // Rollback Transaction
        \DB::rollBack();
        $arr = array("status" => 400, "msg" =>$msg, "result" => array());

   }

Upvotes: 1

Related Questions