Search code examples
laraveltransactionsisolation-level

How to find started transaction?


Controller code:

    public function update(ContractTypeStoreAndUpdateRequest $request, ContractType $contractType): ContractTypeResource
    {
        $contractType->is_active = $request->input('is_active');
        $contractType->name = $request->input('name');
        $contractType->short_name = $request->input('short_name');
        $contractType->description = $request->input('description');
        $pdo = DB::connection()->getPdo();
        $pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
        DB::beginTransaction();
        if ($request->has('feature')) {
            if ($contractType->contracts()->count() !== 0) {
                throw ValidationException::withMessages(
                    [
                        'feature' => 'Тип договора имеет привязанный договор изменить невозможно',
                    ]
                );
            }
            $contractType->feature = $request->input('feature');
        }

        $contractType->save();
        DB::commit();

        return ContractTypeResource::make($contractType);
    }

When I run test on this enpoint I am getting the following error:

Active sql transaction: 1568 Transaction characteristics can't be changed while a transaction is in progress

I understand the error message but I cannot assume where transaction might start before? Do Laravel under the hood do something with transaction (validation, authentication)? How to find the place where transaction has started before?


Solution

  • I got the reason.

    My tests use this trait \Illuminate\Foundation\Testing\DatabaseTransactions

    It covers test in transaction. In the end does rollback to keep database clean.