Laravel database Transaction Rollback

Source: Internet
Author: User
Tags getmessage

Background: The recent use of Laravel-5.4 for project development involves data manipulation of the associated model and the thought of rolling back with a transaction. The middle involves the data reference and the catch of the exception.

There are two ways to roll back a database transaction: automatic rollback, manual rollback.

Examples are as follows:

Automatic rollback

    function (request  $request) {           db::transaction (function  ()  use  ($request)  {          try {            $admin  =  admin::create ([' Name '  =>  $request->name,  ' password '  => encrypt ($ Request->password),  ' email '  =>  $request->email]);           $admin->roles ()->attach ($request->role_id);          //     $admin->roles ()->attach (' SD ');//intentional input of the wrong parameter type, commit failed           return  ' Success ';        } catch  (\exception  $exception)  {          return  $exception->getmeSsage ();        }        });     }

You need to request data $request using the use reference. Otherwise the error "Undefined variable:request"


Manual rollback

    function (request  $request) {        db:: BeginTransaction ();        try {              $admin  = admin::create ([' Name '  =>  $request- >name,  ' Password '  => encrypt ($request->password),  ' email '  => $ Request->email]);             $admin->roles () ->attach ($request->role_id);                     db::commit ();             return  ' success ';         } catch   (\exception  $exception)  {             db::rollback ();             return  $exception->getmessage ();         }    }


Laravel database Transaction Rollback

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.