I have many functions that need to use transaction when save or update data into database.
public function saveMultiple($param1, $param2)
{
DB::beginTransaction();
try {
// save into table 1
// save into table 2
DB::commit();
return true;
} catch (\Throwable $th) {
DB::rollBack();
return false;
}
}
Instead of writing try catch block to every function, Is there a way to separate try catch block as new function and want to inject database save/update code into that function. I'm not sure it is possible or not. Similar like this Link but, it is for javascript. I have no idea it can implement in laravel or not because I don't have much experience with laravel. I appreciate for any advice.
Following is what I tried. Now, I have created new class file call DBaccess.php and create a common function for try catch. The reason why I created new class because I want to access this try catch common function from different classes.
<?php
namespace Test\Libraries\StandardLibraries;
use Illuminate\Support\Facades\DB;
use Exception;
use Illuminate\Support\Facades\Log;
Class DBaccess{
public function transactionWrapper($action)
{
DB::beginTransaction();
try {
$action;
DB::commit();
$result = true;
}
catch (\Throwable $e) {
DB::rollBack();
Log::channel('debuglog')->debug($e->getMessage(). ' in file '.__FILE__.' at line '.__LINE__.' within the class '.get_class());
$result = false;
}
return $result;
}
}
And then, instantiate that DBaccess class and try to inject function that need to save/update/delete data into database as shown in below.
<?php
namespace App\Repositories;
use Test\Libraries\StandardLibraries\DBaccess;
use App\Models\Approver;
use App\Models\User;
use App\Repositories\Interfaces\ApproverRepositoryInterface;
class ApproverRepository implements ApproverRepositoryInterface
{
public function saveMultiple($param1, $param2)
{
// object injection way
$db = new DBaccess;
$all = $db->transactionWrapper($this->newSaveApplicantAndApprover($param1, $param2));
return $all;
}
public function newSaveApplicantAndApprover($param1, $param2)
{
Approver::insert($param1);
User::insert($param1, $param2);
}
}
Inside of saveMultiple()
method, I instantiate DBaccess class and try to inject newSaveApplicantAndApprover()
method(this is the real data saving method) into transactionWrapper()
method.
But, it doesn't work correctly becoz if something wrong in newSaveApplicantAndApprover()
method, data is not roll back correctly.