I must confess that I hadn't considered DB transactions this seriously until recently! I was planning to implement DB transactions once all the basic functionalities had been developed.
While testing the app that I developed, I started to encounter issues with partially inserted data. Sometimes, I missed partial data, and other times, attachments were missing.
Upon researching, I found that a simple piece of code could save me from this nightmare:
DB::transaction(function(){...});
Let's take an example of a Company
After inserting basic informations to the Company, we may need to insert related data into tables like CompanyDetails, CompanyHistory or CompanyUsers.
If an exception or error happens after inserting to the companies
table, rest of the insertions will not work, and we will endup with incomplete 'Company' data!
To handle this we can use the DB transaction method as follows
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
$company = Company::create(['name' => 'LaravelAssist']);
$company->companyDetails()->create(['domain' => 'programming', 'type' => 'online']);
$company->companyHistory()->create(['type' => 'created']);
//...
});
So if any of the insertion fails, the whole insertions are rolled back.
You simply has to enclose it in DB::transaction() method.
You can read more details in official Laravel Documentation.
Note:
When a rollback happens, the auto-increment ID will be lost. The next successful insertion will continue from the last ID + 1.