Sep 18, 2024
0
Level 8
How to delete several related rows under transaction ?
In laravel 11 / livewire 3.5 app I have a form with 2 tables updates : branch and location :
public static function form(Form $form): Form
{
return $form
->schema([
Fieldset::make('Editor')
->schema([
TextInput::make('id')->disabled()->dehydrated(false)
->visible(fn(?Branch $record) => $record !== null),
TextInput::make('name')->lazy()
->required()
->minLength(3)
->maxLength(100)
->unique(table: Branch::class, column: 'name', ignoreRecord: true)
->live()
->afterStateUpdated(fn(Set $set, ?string $state) => $set('slug', Str::slug($state)))
->autofocus()
->placeholder('Enter name of branch'),
TextInput::make('slug')->lazy()
->maxLength(100)
->unique(table: Branch::class, column: 'slug', ignoreRecord: true),
Placeholder::make('active_babel')
->label('Status')
->content(fn(?Branch $record) => 'On creation new branch would be inactive')
->visible(fn(?Branch $record) => ($record === null))
->hint('Managers can work only in active branch'),
Placeholder::make('active')
->label('Status')
->content(fn(Branch $record
) => BranchActiveEnum::getActiveLabel($record->active))
->visible(fn(?Branch $record
) => ($record !== null))
->hint('Managers can work only in active branch'),
]), // Fieldset::make('Editor')
/* Block to related Location START */
Fieldset::make('Location')
->relationship('location')
->schema([
TextInput::make('place')->lazy()
->required()
->minLength(3)
->maxLength(100)
->placeholder('Enter place of location'),
TextInput::make('lat')->lazy()
->required()
->numeric()
->placeholder('Enter valid lat value'),
TextInput::make('lng')->lazy()
->required()
->numeric()
->placeholder('Enter valid lng value '),
Select::make('country')->label('Country')
->prefixIcon(getLocationIcon())
->preload()
->options(ProfileHelper::getCountrySelectionItems(false))
->default(ProfileHelper::getDefaultCountry())
->helperText('Select one countries which are used in the app '),
]), // Fieldset::make('Location')
/* Block to related Location START */
Creating new branch I need to save it under transaction and I managed with this link :
as I added line :
protected ?bool $hasDatabaseTransactions = true;
in both create and edit pages. It works, but I have questions :
a) In case of error if rollback would be raised ? b) Checking sql-tracement I see that deleting are not under transaction.
Deleted implemented in branch model :
protected static function boot()
{
parent::boot();
static::deleted(function ($branch) {
$location = Location::getByModelType(Branch::class)->getByModelId($branch->id)->first();
if ( ! empty($location)) {
$location->delete();
}
});
}
As that is morph relation I can not delete rows in db...
Howcan I run deleted under transaction ?
Please or to participate in this conversation.