### Install Filament Activity Log and Spatie Activity Log Packages Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Installs the necessary Composer packages for Filament Activity Log and Spatie's Laravel Activity Log. It also publishes Spatie's migration and config files and runs the migrations to set up the database tables. ```bash # Install via Composer composer require pxlrbt/filament-activity-log # Also requires Spatie's activity log package composer require spatie/laravel-activitylog # Publish Spatie's migrations and config php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations" php artisan migrate ``` -------------------------------- ### Install Package via Composer Source: https://github.com/pxlrbt/filament-activity-log/blob/main/readme.md This command installs the filament-activity-log package using Composer. It requires PHP 8.0 and Filament 2.0 or higher. ```bash composer require pxlrbt/filament-activity-log ``` -------------------------------- ### Local Development Installation via Composer Path Repository Source: https://github.com/pxlrbt/filament-activity-log/blob/main/readme.md This JSON configuration for `composer.json` allows for local development by pointing to a local path for the 'pxlrbt/filament-activity-log' package. This is useful when contributing or testing changes directly from a fork. ```json { "require": { "pxlrbt/filament-activity-log": "dev-fix/error-message as main-dev", }, "repositories": [ { "type": "path", "url": "filament-activity-log" } ] } ``` -------------------------------- ### Create Activity Log Page in Filament Resource Source: https://github.com/pxlrbt/filament-activity-log/blob/main/readme.md Example of creating a custom page within a Filament resource to display activity logs. This page extends the `ListActivities` class from the package. ```php canRestoreActivity()) { abort(403); } $activity = $this->record->activities()->whereKey($key)->first(); $oldProperties = data_get($activity, 'properties.old'); if ($oldProperties === null) { $this->sendRestoreFailureNotification('No previous state available'); return; } try { // Custom pre-restore logic logger()->info('Restoring order', [ 'order_id' => $this->record->id, 'activity_id' => $key, 'restored_by' => auth()->id() ]); $this->record->update($oldProperties); // Custom post-restore logic $this->record->notes()->create([ 'content' => 'Order restored to previous state', 'user_id' => auth()->id() ]); $this->sendRestoreSuccessNotification(); } catch (Exception $e) { $this->sendRestoreFailureNotification($e->getMessage()); } } } ``` -------------------------------- ### PHP Custom Activity Filtering in Filament Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Demonstrates how to customize the activities displayed in Filament by extending the ListActivities page. This example filters out 'deleted' events and only shows activities with actual property changes. It also configures cursor pagination for performance. ```php paginateQuery( $this->record->activities() ->with('causer') ->where('event', '!=', 'deleted') // Hide delete events ->whereNotNull('properties->attributes') // Only show actual changes ->latest() ->getQuery() ); } // Use cursor pagination for better performance public function getPaginationMode(): PaginationMode { return PaginationMode::Cursor; } } ``` -------------------------------- ### PHP Custom Translation Override for Filament Activity Log Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Allows overriding default Filament Activity Log translations for a specific locale, such as English. This example shows how to customize labels for table columns, events, and provides a US-style datetime format. Place this file in resources/lang/vendor/filament-activity-log/en/activities.php. ```php 'Change Log', 'title' => 'Audit Trail for :record', 'default_datetime_format' => 'm/d/Y g:i A', // US format with AM/PM 'table' => [ 'field' => 'Attribute', 'old' => 'Previous Value', 'new' => 'Current Value', 'restore' => 'Rollback', ], 'events' => [ 'updated' => 'Modified', 'created' => 'Added', 'deleted' => 'Removed', 'restored' => 'Rolled Back', 'restore_successful' => 'Successfully rolled back to previous state', 'restore_failed' => 'Rollback operation failed', ], ]; ``` -------------------------------- ### Link to Activity Page from Filament Table Source: https://github.com/pxlrbt/filament-activity-log/blob/main/readme.md Shows how to add an action to a Filament table that links to the activity log page for a specific record. It uses `Action::make()` and `getUrl()` to generate the link. ```php $table->actions([ Action::make('activities')->url(fn ($record) => YourResource::getUrl('activities', ['record' => $record])) ]); ``` -------------------------------- ### Configure Tailwind CSS for Filament Activity Log Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Sets up Tailwind CSS configuration to include the necessary paths for Filament and the Filament Activity Log package. This ensures styles are correctly processed. ```json // tailwind.config.js export default { content: [ './resources/**/*.blade.php', './vendor/filament/**/*.blade.php', './vendor/pxlrbt/filament-activity-log/resources/**/*.blade.php', ], // ... rest of config } ``` -------------------------------- ### Programmatic Activity Retrieval with Spatie Activitylog Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt This PHP code demonstrates how to retrieve activity logs programmatically for a given model (e.g., Order) using the Spatie Activitylog package. It shows how to fetch all activities, recent activities with user info, filter by event type or date range, and access individual activity details like event, user, and changes made. ```php activities; // Get latest 10 activities with user info $recentActivities = $order->activities() ->with('causer') ->latest() ->limit(10) ->get(); // Find specific activity types $updateActivities = $order->activities() ->where('event', 'updated') ->get(); // Get activities within date range $activitiesThisMonth = $order->activities() ->whereBetween('created_at', [now()->startOfMonth(), now()->endOfMonth()]) ->get(); // Access activity details foreach ($activities as $activity) { echo "Event: " . $activity->event . "\n"; echo "User: " . $activity->causer?->name . "\n"; echo "Changes: " . json_encode($activity->properties['attributes'] ?? []) . "\n"; echo "Old values: " . json_encode($activity->properties['old'] ?? []) . "\n"; } ``` -------------------------------- ### Import Filament Activity Log Styles into Theme Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Imports the necessary CSS styles for the Filament Activity Log into your custom Filament theme. This ensures the activity log interface is styled correctly. ```css /* resources/css/filament/admin/theme.css */ @import '../../../../vendor/pxlrbt/filament-activity-log/resources/css/styles.css'; @config 'tailwind.config.js'; ``` -------------------------------- ### Register Activity Page in Resource Pages Source: https://github.com/pxlrbt/filament-activity-log/blob/main/readme.md Demonstrates how to register the custom activity log page within the `getPages()` method of a Filament resource. This makes the page accessible via a route. ```php public static function getPages(): array { return [ 'index' => Pages\ListOrders::route('/'), 'create' => Pages\CreateOrder::route('/create'), 'activities' => Pages\ListOrderActivities::route('/{record}/activities'), 'edit' => Pages\EditOrder::route('/{record}/edit'), ]; } ``` -------------------------------- ### Manual Activity Creation with Spatie Activitylog Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt This PHP code shows how to manually log custom activities using the Spatie Activitylog package. It covers logging a custom activity with additional properties and logging an activity with a specific custom event type, both associated with a particular model and optionally caused by a user. ```php performedOn($order) ->causedBy(auth()->user()) ->withProperties(['custom_field' => 'custom_value']) ->log('Custom activity logged'); // Log with specific event type activity('custom_event') ->performedOn($order) ->log('Custom event logged'); ``` -------------------------------- ### Configure Eloquent Model for Activity Logging Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Configures an Eloquent model to use Spatie's `LogsActivity` trait and defines logging options. It specifies which attributes to log, only logs dirty attributes, and prevents empty logs. ```php logOnly(['order_number', 'customer_name', 'total', 'status']) ->logOnlyDirty() ->dontSubmitEmptyLogs(); } } ``` -------------------------------- ### Filament Contract Resource Integration Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt This PHP code defines a Filament resource for a 'Contract' model. It includes form schema for creating and editing contracts, table columns for displaying contract data, actions like viewing history, and defines page routes. It also implements a 'canRestore' method to control record restoration based on status and user permissions. ```php schema([ TextInput::make('contract_number') ->label('Contract Number') ->required(), Select::make('client_id') ->label('Client') ->relationship('client', 'name') ->searchable() ->required(), DatePicker::make('start_date') ->label('Start Date') ->required(), DatePicker::make('end_date') ->label('End Date') ->required(), TextInput::make('value') ->label('Contract Value') ->numeric() ->prefix('$'), Select::make('status') ->label('Status') ->options([ 'draft' => 'Draft', 'active' => 'Active', 'completed' => 'Completed', 'cancelled' => 'Cancelled', ]) ->required(), Textarea::make('terms') ->label('Contract Terms') ->rows(5), ]); } public static function table(Table $table): Table { return $table ->columns([ TextColumn::make('contract_number')->searchable(), TextColumn::make('client.name')->searchable(), TextColumn::make('start_date')->date(), TextColumn::make('status')->badge(), ]) ->actions([ Action::make('history') ->label('History') ->icon('heroicon-o-clock') ->color('gray') ->url(fn ($record) => self::getUrl('activities', ['record' => $record])) ->tooltip('View change history'), ]); } public static function getPages(): array { return [ 'index' => Pages\ListContracts::route('/'), 'create' => Pages\CreateContract::route('/create'), 'edit' => Pages\EditContract::route('/{record}/edit'), 'activities' => Pages\ListContractActivities::route('/{record}/activities'), ]; } public static function canRestore(Model $record): bool { // Only allow restore for drafts and active contracts return in_array($record->status, ['draft', 'active']) && auth()->user()->can('update', $record); } } ``` -------------------------------- ### Create Filament Activity Log Page Class Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Defines a custom Filament page class that extends `ListActivities` to display activity logs for a specific resource. It allows for customization of the page title and breadcrumb. ```php setLocale('de'); // German translation example from resources/lang/de/activities.php return [ 'breadcrumb' => 'Verlauf', 'title' => 'Verlauf :record', 'default_datetime_format' => 'd.m.Y, H:i:s \U\h\r', 'table' => [ 'field' => 'Feld', 'old' => 'Alt', 'new' => 'Neu', 'restore' => 'Wiederherstellen', ], 'events' => [ 'updated' => 'Aktualisiert', 'created' => 'Erstellt', 'deleted' => 'Gelöscht', 'restored' => 'Wiederhergestellt', 'restore_successful' => 'Erfolgreich wiederhergestellt', 'restore_failed' => 'Wiederherstellung fehlgeschlagen', ], ]; ``` -------------------------------- ### Session-Persistent Pagination in Filament Activity Log Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Demonstrates how Filament Activity Log automatically stores pagination preferences in the session. This ensures that a user's selected record count per page persists across navigation and refreshes. ```php get('pages.5d41402abc4b2a76b9719d911017c592_per_page') // User selects 50 records per page // This preference persists across page refreshes and navigation // Each activity log page class maintains its own pagination preference ``` -------------------------------- ### Enable Restore Functionality for Records in Filament Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Shows how to enable the record restoration feature in Filament by implementing the `canRestore` method within a resource. This method controls which users or roles have the permission to restore deleted records. ```php user()->hasRole('admin'); // Or use Laravel policies // return auth()->user()->can('restore', $record); } } ``` -------------------------------- ### Automatic Field Label Resolution in Filament Forms Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Illustrates Filament's automatic resolution of field labels based on the field names defined in the form schema. This simplifies label management by inferring labels from column names. ```php schema([ TextInput::make('first_name') ->label('First Name') // Activity log will show "First Name" instead of "first_name" ->required(), TextInput::make('email') ->label('Email Address') // Shows as "Email Address" ->email(), Select::make('role_id') ->label('User Role') // Shows as "User Role" ->relationship('role', 'name'), ]); } } ``` -------------------------------- ### Link to Activity Log Page from Table Actions Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Adds a table action to display a link to the activity log page for a specific record. This allows users to easily navigate to the history of a record directly from the resource's table. ```php use Filament\Tables\Actions\Action; use Filament\Tables\Table; public static function table(Table $table): Table { return $table ->columns([ // ... your columns ]) ->actions([ Action::make('view_activities') ->label('History') ->icon('heroicon-o-clock') ->url(fn ($record) => OrderResource::getUrl('activities', ['record' => $record->id])) ->openUrlInNewTab(), // ... other actions ]); } ``` -------------------------------- ### PHP Including Related Model Activities in Filament Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Shows how to display activities not only for a primary record but also for its related models, such as tasks associated with a project. This involves querying activities where the subject type matches the project or its tasks. ```php record->tasks()->pluck('id'); return $this->paginateQuery( \Spatie\Activitylog\Models\Activity::query() ->with('causer') ->where(function ($query) use ($taskIds) { $query->where(function ($q) { $q->where('subject_type', $this->record->getMorphClass()) ->where('subject_id', $this->record->id); }) ->orWhere(function ($q) use ($taskIds) { $q->where('subject_type', \App\Models\Task::class) ->whereIn('subject_id', $taskIds); }); }) ->latest() ->getQuery() ); } } ``` -------------------------------- ### Register Activity Log Page in Filament Resource Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Registers the custom activity log page within a Filament resource's page definitions. This makes the activity log accessible via a specific route within the resource. ```php Pages\ListOrders::route('/'), 'create' => Pages\CreateOrder::route('/create'), 'edit' => Pages\EditOrder::route('/{record}/edit'), 'activities' => Pages\ListOrderActivities::route('/{record}/activities'), ]; } // Required for restore functionality public static function canRestore(Model $record): bool { return auth()->user()->can('update', $record); } } ``` -------------------------------- ### Override Pagination Settings in Filament Activity Log Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Customize the default number of records per page and the selectable options for pagination in the Filament Activity Log. This allows for better control over data display and user experience. ```php 'array', 'tags' => 'array', 'price_tiers' => 'json', ]; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['name', 'sku', 'price', 'metadata', 'tags', 'price_tiers']) ->logOnlyDirty(); } } // Activity log automatically handles JSON/array fields // Display example in activity log: // Field: metadata // Old: {"color": "blue", "size": "large"} // New: {"color": "red", "size": "medium", "weight": "500g"} ``` -------------------------------- ### Log Custom Accessors in Filament Activity Log (PHP) Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Demonstrates how to log virtual attributes derived from custom accessors within a Laravel Eloquent model using Spatie's Activitylog. By including the accessor's attribute name (e.g., 'full_name') in the `logOnly` array of `getActivitylogOptions`, changes to the underlying fields that affect the accessor will be captured in the activity log. ```php first_name} {$this->last_name}"; } public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logOnly(['first_name', 'last_name', 'full_name', 'salary']) ->logOnlyDirty(); } } // When first_name or last_name changes, full_name changes will also be logged ``` -------------------------------- ### Override Filament Activity Log Restore Notifications (PHP) Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Customizes the success and failure notifications displayed by Filament for document restore operations. This involves extending the base ListActivities page and redefining the notification methods. It utilizes Filament's Notification system for rich user feedback. ```php title('Document Restored') ->body("Document '{$this->record->title}' has been restored to a previous version.") ->icon('heroicon-o-clock-rotate-left') ->success() ->duration(5000) ->send(); } // Customize failure notification with detailed error protected function sendRestoreFailureNotification(?string $message = null): Notification { return Notification::make() ->title('Restore Operation Failed') ->body($message ?? 'Unable to restore document. Please contact support if the issue persists.') ->icon('heroicon-o-exclamation-triangle') ->danger() ->persistent() ->actions([ \Filament\Notifications\Actions\Action::make('contact_support') ->button() ->url('/support'), ]) ->send(); } } ``` -------------------------------- ### Custom Field Label Override for Filament Activity Log Source: https://context7.com/pxlrbt/filament-activity-log/llms.txt Demonstrates how to override default field labels for the Filament Activity Log by implementing the `getFieldLabel` method. This is useful for fields that do not have direct form mapping or require specific display names. ```php 'Tax Amount (Calculated)', 'shipping_method' => 'Delivery Method', 'internal_notes' => 'Staff Notes (Internal)', ]; if (isset($customLabels[$name])) { return $customLabels[$name]; } // Fall back to default behavior return parent::getFieldLabel($name); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.