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.
Laravel Filament Admin Resource - Toggle Entire Table Column Hooks
<?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]);
}
}
}
<?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]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment