TarikAli's avatar

Refactor function and DB Transaction

Hello, i have this function in a service :

I want to use DB::Transaction to store option with values or rollback all

first: can we refactor this function second: can i use DB::Transaction in a service or in the controller

0 likes
3 replies
tykus's avatar

I want to use DB::Transaction to store option with values or rollback all

Why do you need a transaction here; what is the context, where is this createOptionWithValues method used?

TarikAli's avatar

it creats values with this option (master details table) in the same service

    public function createValue(Option $option, array $value): OptionValue
    {
        $optionValue = new OptionValue();
        $optionValue->option_id = $option->id;
        $optionValue->fill($this->mapOptionValue($value));
        $optionValue->save();

        return $optionValue;
    }
tykus's avatar

What Exception(s) are you expecting in this scenario; is there something else happening other than new records being written to the database?

In response to your original question, you can put the transaction anywhere, in the Service class method or the Controller action depending on what else you need to wrap within the transaction. Just be mindful nesting transactions is not possible for many RDBMS.

Please or to participate in this conversation.