Use database transactions in Laravel and catch exceptions after transaction failures

Source: Internet
Author: User
Description in Laravel, to run a group of operations in database transactions, you can use the transaction method in DBfacade. If an exception is thrown in the closure of a transaction, the transaction will be automatically restored. If the closure runs successfully, the transaction is automatically committed. You don't need to worry about

To run a group of operations in a database transaction in Laravel, you can use the transaction method in DB facade. If an exception is thrown in the closure of a transaction, the transaction will be automatically restored. If the closure runs successfully, the transaction is automatically committed. You do not need to worry about manually restoring or committing transactions when using the transaction method:

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

Manual transaction operations

If you want to manually process the transaction and fully control the restore or commit operations, you can usebeginTransactionMethod:

DB::beginTransaction();

You can also use the rollBack method to restore the transaction:

DB::rollBack();

Finally, you can submit the transaction using the commit method:

DB::commit();

Note: The transaction method of DB facade can also be used to control the transaction of the query statement constructor and Eloquent ORM.

Example

Assume that you want to store a knowledge point in the database. this knowledge point belongs to two different test sites at the same time, that is, the data of the test site and Knowledge Point are many-to-many relationships, to implement this data structure, three tables are required:

Knowledge Point table wiki:

---------------------------------------id       title              content---------------------------------------

Test site table tag:

-------------------id       name-------------------

Test site knowledge point Association table wiki_tag_rel

----------------------------------id          tag_id        wiki_id----------------------------------

Now you need to enable the new Wiki data for the transaction. after successfully adding the wiki, you can associate it with the specified test site.

(Illuminate \ Database \ QueryException is returned if query Builder or Eloquent ORM is used in laravel to execute query)

 Get ('tag _ id'); $ wiki_id = DB: table ('wiki ') -> insertGetId (['title' => $ request-> get ('title'), 'content' => $ 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']);} // use the transaction method of DB facade to control the public function createWiki (array $ data) {DB: beginTransaction (); try {$ tagIds = explode (',', $ data ['tag _ id']); $ newWiki = Wiki: create (['title' => $ data ['title'], 'content' => $ data ['content']); // The two models of Wiki and Tag use belongsToMany to establish a many-to-many relationship // attach the relationship between wiki and tag through the attach method (write to the intermediate table) $ newWiki-> tags ()-> 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

To run a group of operations in a database transaction in Laravel, you can use the transaction method in DB facade. If an exception is thrown in the closure of a transaction, the transaction will be automatically restored. If the closure runs successfully, the transaction is automatically committed. You do not need to worry about manually restoring or committing transactions when using the transaction method:

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

Manual transaction operations

If you want to manually process the transaction and fully control the restore or commit operations, you can usebeginTransactionMethod:

DB::beginTransaction();

You can also use the rollBack method to restore the transaction:

DB::rollBack();

Finally, you can submit the transaction using the commit method:

DB::commit();

Note: The transaction method of DB facade can also be used to control the transaction of the query statement constructor and Eloquent ORM.

Example

Assume that you want to store a knowledge point in the database. this knowledge point belongs to two different test sites at the same time, that is, the data of the test site and Knowledge Point are many-to-many relationships, to implement this data structure, three tables are required:

Knowledge Point table wiki:

---------------------------------------id       title              content---------------------------------------

Test site table tag:

-------------------id       name-------------------

Test site knowledge point Association table wiki_tag_rel

----------------------------------id          tag_id        wiki_id----------------------------------

Now you need to enable the new Wiki data for the transaction. after successfully adding the wiki, you can associate it with the specified test site.

(Illuminate \ Database \ QueryException is returned if query Builder or Eloquent ORM is used in laravel to execute query)

 Get ('tag _ id'); $ wiki_id = DB: table ('wiki ') -> insertGetId (['title' => $ request-> get ('title'), 'content' => $ 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']);} // use the transaction method of DB facade to control the public function createWiki (array $ data) {DB: beginTransaction (); try {$ tagIds = explode (',', $ data ['tag _ id']); $ newWiki = Wiki: create (['title' => $ data ['title'], 'content' => $ data ['content']); // The two models of Wiki and Tag use belongsToMany to establish a many-to-many relationship // attach the relationship between wiki and tag through the attach method (write to the intermediate table) $ newWiki-> tags ()-> 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']);}

For more articles about using database transactions in Laravel and capturing exceptions after a transaction failure, refer to PHP!

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.