Using database transactions in Laravel and catching exceptions after failed transactions

Source: Internet
Author: User

Description

In Laravel to run a set of operations in a database transaction, you can use the transaction method in db facade. If an exception is thrown within the closure of a transaction, the transaction is automatically restored. If the closure runs successfully, the transaction is automatically committed. You don't have to worry about the need to manually restore or commit a transaction when using the transaction method:

Db::transaction (function () {    db::table (' users ')->update ([' votes ' = 1]);    Db::table (' posts ')->delete ();});

Manually Manipulating transactions

If you want to handle transactions manually and have full control over the restore or commit operation, you can use the method in DB facade beginTransaction :

Db::begintransaction ();

You can also restore transactions by using the RollBack method:

Db::rollback ();

Finally, you can commit the transaction through the Commit method:

Db::commit ();

Note: The transaction method of the DB facade can also be used to control query-statement constructors and eloquent ORM transactions.

Example

If there is a knowledge point to store in the database, this knowledge point belongs to two different test centers, that is, the test center and the knowledge point of the two data is a many-to-many relationship, then to achieve this data structure requires three tables:

Knowledge Point Table Wiki:

---------------------------------------ID       title              content---------------------------------------

Test Center Table Tag:

-------------------ID       Name-------------------

Knowledge Point Association Table Wiki_tag_rel

----------------------------------ID          tag_id        wiki_id----------------------------------

Now to open the transaction new wiki data, the new wiki is successful and then link it to the designated Test center up

(When using Query Builder in Laravel or eloquent ORM to execute query, if failure returns a Illuminate\database\queryexception exception)

<?phpnamespace app\http\controllers;use illuminate\http\request;use illuminate\database\queryexception;use App\ Wiki;class TestController extends controller{//transaction method with DB facade controls the transaction public function Storewiki of the query statement builder (Request $requ        EST) {db::begintransaction ();            try {$tagIds = explode (', ', $request->get (' tag_id ')); $wiki _id = db::table (' wiki ')->insertgetid ([' title ' = + $request->get (' title '), ' con            Tent ' = $request->get (' content ')]);            $relationData = [];                foreach ($tagIds as $tagId) {$data = [' wiki_id ' = $wiki _id, ' tag_id ' + $tagId];            $relationData [] = $data;            } db::table (' Wiki_tag_rel ')->insert ($relationData);        Db::commit ();            } catch (\illuminate\database\queryexception $ex) {db::rollback (); return \response::json ([' status ' = ' error ', ' error_msg ' = ' Failed ', pLease Contact Supervisor ']);    } return \response::json ([' status ' = ' OK ']);        The transaction public function Createwiki (array $data) {db::begintransaction () eloquent ORM is controlled by the transaction method of the DB facade;            try {$tagIds = explode (', ', $data [' tag_id ']);            $newWiki = Wiki::create ([' title ' = ' + ' $data [' title '], ' content ' + $data [' content ']            ]); The wiki and tag two model use Belongstomany to establish a many-to-many relationship//attach method to attach the relationship between wiki and tag (write to Intermediate table) $newWiki->tags ()-&gt            ; Attach ($tagIds);        Db::commit ();            } catch (Queryexception $ex) {db::rollback ();        return \response::json ([' status ' = ' error ', ' error_msg ' = ' Failed ', please contact Supervisor ']);     } return \response::json ([' status ' = ' OK ']); }}

Description

In Laravel to run a set of operations in a database transaction, you can use the transaction method in db facade. If an exception is thrown within the closure of a transaction, the transaction is automatically restored. If the closure runs successfully, the transaction is automatically committed. You don't have to worry about the need to manually restore or commit a transaction when using the transaction method:

Db::transaction (function () {    db::table (' users ')->update ([' votes ' = 1]);    Db::table (' posts ')->delete ();});

Manually Manipulating transactions

If you want to handle transactions manually and have full control over the restore or commit operation, you can use the method in DB facade beginTransaction :

Db::begintransaction ();

You can also restore transactions by using the RollBack method:

Db::rollback ();

Finally, you can commit the transaction through the Commit method:

Db::commit ();

Note: The transaction method of the DB facade can also be used to control query-statement constructors and eloquent ORM transactions.

Example

If there is a knowledge point to store in the database, this knowledge point belongs to two different test centers, that is, the test center and the knowledge point of the two data is a many-to-many relationship, then to achieve this data structure requires three tables:

Knowledge Point Table Wiki:

---------------------------------------ID       title              content---------------------------------------

Test Center Table Tag:

-------------------ID       Name-------------------

Knowledge Point Association Table Wiki_tag_rel

----------------------------------ID          tag_id        wiki_id----------------------------------

Now to open the transaction new wiki data, the new wiki is successful and then link it to the designated Test center up

(When using Query Builder in Laravel or eloquent ORM to execute query, if failure returns a Illuminate\database\queryexception exception)

<?phpnamespace app\http\controllers;use illuminate\http\request;use illuminate\database\queryexception;use App\ Wiki;class TestController extends controller{//transaction method with DB facade controls the transaction public function Storewiki of the query statement builder (Request $requ        EST) {db::begintransaction ();            try {$tagIds = explode (', ', $request->get (' tag_id ')); $wiki _id = db::table (' wiki ')->insertgetid ([' title ' = + $request->get (' title '), ' con            Tent ' = $request->get (' content ')]);            $relationData = [];                foreach ($tagIds as $tagId) {$data = [' wiki_id ' = $wiki _id, ' tag_id ' + $tagId];            $relationData [] = $data;            } db::table (' Wiki_tag_rel ')->insert ($relationData);        Db::commit ();            } catch (\illuminate\database\queryexception $ex) {db::rollback (); return \response::json ([' status ' = ' error ', ' error_msg ' = ' Failed ', pLease Contact Supervisor ']);    } return \response::json ([' status ' = ' OK ']);        The transaction public function Createwiki (array $data) {db::begintransaction () eloquent ORM is controlled by the transaction method of the DB facade;            try {$tagIds = explode (', ', $data [' tag_id ']);            $newWiki = Wiki::create ([' title ' = ' + ' $data [' title '], ' content ' + $data [' content ']            ]); The wiki and tag two model use Belongstomany to establish a many-to-many relationship//attach method to attach the relationship between wiki and tag (write to Intermediate table) $newWiki->tags ()-&gt            ; Attach ($tagIds);        Db::commit ();            } catch (Queryexception $ex) {db::rollback ();        return \response::json ([' status ' = ' error ', ' error_msg ' = ' Failed ', please contact Supervisor ']);     } return \response::json ([' status ' = ' OK ']); }}

More about using database transactions in Laravel and capturing exception related articles after failed transactions please follow topic.alibabacloud.com!

  • 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.