Skip to content

Instantly share code, notes, and snippets.

@MACscr
Created January 16, 2022 01:30
Show Gist options
  • Save MACscr/5eb27b22d9e2b7096046bd75d43c4ae5 to your computer and use it in GitHub Desktop.
Save MACscr/5eb27b22d9e2b7096046bd75d43c4ae5 to your computer and use it in GitHub Desktop.

Revisions

  1. MACscr created this gist Jan 16, 2022.
    21 changes: 21 additions & 0 deletions CreatePlan.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    <?php

    namespace App\Filament\Resources\PlanResource\Pages;

    use App\Filament\Resources\PlanResource;
    use App\Models\Plan;
    use Filament\Resources\Pages\CreateRecord;

    class CreatePlan extends CreateRecord
    {
    protected static string $resource = PlanResource::class;

    protected function afterCreate(): void
    {
    // Runs after the form fields are created in the database.
    // if record has default set to 1, set all other records to 0
    if (true === $this->record->default) {
    Plan::where('id', '!=', $this->record->id)->update(['default' => 0]);
    }
    }
    }
    30 changes: 30 additions & 0 deletions EditPlan.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    <?php

    namespace App\Filament\Resources\PlanResource\Pages;

    use App\Filament\Resources\PlanResource;
    use App\Models\Plan;
    use Filament\Resources\Pages\EditRecord;

    class EditPlan extends EditRecord
    {
    protected static string $resource = PlanResource::class;

    protected function afterSave(): void
    {
    // Runs after the form fields are saved to the database.
    // if record has default set to 1, set all other records to 0
    if (true === $this->record->default) {
    Plan::where('id', '!=', $this->record->id)->update(['default' => 0]);
    }
    }

    protected function afterDelete(): void
    {
    // Runs after the record is deleted.
    // Need to have at least one Plan with a default value of 1. Picks latest plan.
    if (0 == Plan::where(['default' => 1])->count()) {
    Plan::orderBy('id', 'desc')->take(1)->update(['default' => 1]);
    }
    }
    }