Skip to content

Commit bdd201f

Browse files
author
farhadzand
committed
update query scopes
1 parent 9c15f74 commit bdd201f

File tree

2 files changed

+128
-33
lines changed

2 files changed

+128
-33
lines changed

README.md

Lines changed: 90 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -289,20 +289,44 @@ The audit logger automatically tracks the source of changes to help with debuggi
289289
]
290290
```
291291

292-
You can query audit logs by source to track changes from specific commands or controllers:
292+
You can query audit logs by source using convenient scopes:
293293

294294
```php
295295
use iamfarhad\LaravelAuditLog\Models\EloquentAuditLog;
296296

297+
// Using dedicated source scopes for cleaner queries
298+
297299
// Find all changes made by a specific console command
298-
$commandLogs = EloquentAuditLog::where('source', 'app:send-emails')->get();
300+
$commandLogs = EloquentAuditLog::forEntity(User::class)
301+
->fromCommand('app:send-emails')
302+
->get();
303+
304+
// Find all changes made through console commands
305+
$consoleLogs = EloquentAuditLog::forEntity(User::class)
306+
->fromConsole()
307+
->get();
308+
309+
// Find all changes made through HTTP requests
310+
$webLogs = EloquentAuditLog::forEntity(User::class)
311+
->fromHttp()
312+
->get();
313+
314+
// Find changes from a specific controller
315+
$controllerLogs = EloquentAuditLog::forEntity(User::class)
316+
->fromController('UserController')
317+
->get();
299318

300-
// Find all changes made through web interface
301-
$webLogs = EloquentAuditLog::where('source', 'like', 'App\\Http\\Controllers\\%')->get();
319+
// Find changes by exact source match
320+
$exactSourceLogs = EloquentAuditLog::forEntity(User::class)
321+
->forSource('app:send-emails')
322+
->get();
302323

303-
// Find changes from console commands
304-
$consoleLogs = EloquentAuditLog::whereNotNull('source')
305-
->where('source', 'not like', 'App\\Http\\Controllers\\%')
324+
// Combine with other scopes
325+
$filteredLogs = EloquentAuditLog::forEntity(User::class)
326+
->fromConsole()
327+
->forAction('updated')
328+
->dateBetween(now()->subWeek(), now())
329+
->orderBy('created_at', 'desc')
306330
->get();
307331
```
308332

@@ -337,24 +361,7 @@ $order->audit()
337361
->log();
338362
```
339363

340-
Alternatively, you can still use the traditional event-driven approach if needed:
341-
342-
```php
343-
<?php
344-
345-
declare(strict_types=1);
346-
347-
use Illuminate\Support\Facades\Event;
348-
use iamfarhad\LaravelAuditLog\Events\ModelAudited;
349-
350-
$order = Order::find(1);
351-
Event::dispatch(new ModelAudited(
352-
model: $order,
353-
action: 'status_changed',
354-
oldValues: ['status' => 'pending'],
355-
newValues: ['status' => 'shipped']
356-
));
357-
```
364+
This approach provides better performance than event-driven architectures since it logs directly to the database without the overhead of event dispatching and listening.
358365

359366
#### Fluent API for Custom Audit Events
360367

@@ -438,7 +445,7 @@ $logs = EloquentAuditLog::forEntity(User::class)
438445

439446
// Use scope to filter by action type
440447
$createdLogs = EloquentAuditLog::forEntity(User::class)
441-
->action('created')
448+
->forAction('created')
442449
->where('entity_id', 1)
443450
->get();
444451

@@ -451,26 +458,31 @@ $lastMonthLogs = EloquentAuditLog::forEntity(User::class)
451458

452459
// Use scope to filter by causer (user who performed the action)
453460
$adminLogs = EloquentAuditLog::forEntity(User::class)
454-
->causer(1) // Assuming causer_id 1 is the admin
461+
->forCauserId(1) // Assuming causer_id 1 is the admin
455462
->where('entity_id', 1)
456463
->get();
457464

458-
// Filter by source (console commands, HTTP routes, etc.)
465+
// Filter by source using dedicated scopes
459466
$consoleLogs = EloquentAuditLog::forEntity(User::class)
460-
->where('source', 'app:send-emails')
467+
->fromCommand('app:send-emails')
461468
->where('entity_id', 1)
462469
->get();
463470

464471
$webLogs = EloquentAuditLog::forEntity(User::class)
465-
->where('source', 'like', 'App\\Http\\Controllers\\%')
472+
->fromHttp()
473+
->where('entity_id', 1)
474+
->get();
475+
476+
$controllerLogs = EloquentAuditLog::forEntity(User::class)
477+
->fromController('UserController')
466478
->where('entity_id', 1)
467479
->get();
468480

469481
// Combine multiple scopes for precise filtering
470482
$filteredLogs = EloquentAuditLog::forEntity(User::class)
471-
->action('updated')
472-
->causer(1)
473-
->where('source', 'app:send-emails')
483+
->forAction('updated')
484+
->forCauserId(1)
485+
->fromCommand('app:send-emails')
474486
->dateBetween(now()->subDays(7), now())
475487
->where('entity_id', 1)
476488
->orderBy('created_at', 'desc')
@@ -480,6 +492,51 @@ $filteredLogs = EloquentAuditLog::forEntity(User::class)
480492

481493
These scopes allow for flexible and efficient querying of audit logs, making it easier to analyze changes based on action type, date range, or the user responsible for the change.
482494

495+
### Available Query Scopes
496+
497+
The `EloquentAuditLog` model provides several convenient scopes for filtering audit logs:
498+
499+
#### Entity and Basic Filtering
500+
- `forEntity(string $entityClass)` - Filter by entity type (e.g., `User::class`)
501+
- `forEntityId($entityId)` - Filter by entity ID
502+
- `forAction(string $action)` - Filter by action (`created`, `updated`, `deleted`, etc.)
503+
- `forCauser(string $causerClass)` - Filter by causer type
504+
- `forCauserId($causerId)` - Filter by causer ID
505+
506+
#### Date Filtering
507+
- `forCreatedAt($createdAt)` - Filter by exact creation date
508+
- `dateGreaterThan($date)` - Filter for logs after a specific date
509+
- `dateLessThan($date)` - Filter for logs before a specific date
510+
- `dateBetween($startDate, $endDate)` - Filter for logs within a date range
511+
512+
#### Source Filtering
513+
- `forSource(string $source)` - Filter by exact source match
514+
- `fromConsole()` - Filter for logs from console commands
515+
- `fromHttp()` - Filter for logs from HTTP requests
516+
- `fromCommand(string $command)` - Filter by specific console command
517+
- `fromController(string $controller = null)` - Filter by controller (or all controllers if no parameter)
518+
519+
```php
520+
// Examples of scope combinations
521+
use iamfarhad\LaravelAuditLog\Models\EloquentAuditLog;
522+
523+
// Complex filtering example
524+
$logs = EloquentAuditLog::forEntity(User::class)
525+
->forAction('updated')
526+
->fromConsole()
527+
->dateBetween(now()->subWeek(), now())
528+
->forCauserId(1)
529+
->orderBy('created_at', 'desc')
530+
->paginate(20);
531+
532+
// Find all user updates from a specific command in the last 24 hours
533+
$recentCommandLogs = EloquentAuditLog::forEntity(User::class)
534+
->forAction('updated')
535+
->fromCommand('app:sync-users')
536+
->dateGreaterThan(now()->subDay())
537+
->get();
538+
```
539+
483540
## Performance Optimization
484541

485542
- **Batch Processing**: Enable batch processing in the configuration to reduce database transactions for high-frequency operations.

src/Models/EloquentAuditLog.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,44 @@ public function scopeDateBetween(Builder $query, $startDate, $endDate): Builder
9999
});
100100
}
101101

102+
public function scopeForSource(Builder $query, string $source): Builder
103+
{
104+
return $query->where('source', $source);
105+
}
106+
107+
public function scopeFromConsole(Builder $query): Builder
108+
{
109+
return $query->whereNotNull('source')
110+
->where('source', 'not like', 'App\\Http\\Controllers\\%')
111+
->where('source', 'not like', 'App\\\\Http\\\\Controllers\\\\%');
112+
}
113+
114+
public function scopeFromHttp(Builder $query): Builder
115+
{
116+
return $query->where(function (Builder $query) {
117+
$query->where('source', 'like', 'App\\Http\\Controllers\\%')
118+
->orWhere('source', 'like', 'App\\\\Http\\\\Controllers\\\\%')
119+
->orWhere('source', '=', 'http');
120+
});
121+
}
122+
123+
public function scopeFromCommand(Builder $query, string $command): Builder
124+
{
125+
return $query->where('source', $command);
126+
}
127+
128+
public function scopeFromController(Builder $query, ?string $controller = null): Builder
129+
{
130+
if ($controller) {
131+
return $query->where('source', 'like', "%{$controller}%");
132+
}
133+
134+
return $query->where(function (Builder $query) {
135+
$query->where('source', 'like', 'App\\Http\\Controllers\\%')
136+
->orWhere('source', 'like', 'App\\\\Http\\\\Controllers\\\\%');
137+
});
138+
}
139+
102140
public static function forEntity(string $entityClass): static
103141
{
104142
$className = Str::snake(class_basename($entityClass));

0 commit comments

Comments
 (0)