Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to manually set created at date #622

Merged
merged 5 commits into from
Feb 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/basic-usage/logging-activity.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,18 @@ $lastActivity->getExtraProperty('key'); //returns 'value'
$lastActivity->where('properties->key', 'value')->get(); // get all activity where the `key` custom property is 'value'
```

## Setting custom created date

You can set a custom activity created_at date time by using `createdAt`

```php
activity()
->causedBy($userModel)
->performedOn($someContentModel)
->createdAt(now()->subDays(10))
->log('created')
```

## Tap Activity before logged

You can use the `tap()` method to fill properties and add custom fields before the activity is saved.
Expand Down
10 changes: 10 additions & 0 deletions src/ActivityLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace Spatie\Activitylog;

use Spatie\String\Str;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Database\Eloquent\Model;
Expand Down Expand Up @@ -104,6 +107,13 @@ public function withProperty(string $key, $value)
return $this;
}

public function createdAt(Carbon $dateTime)
{
$this->getActivity()->created_at = $dateTime;

return $this;
}

public function useLog(string $logName)
{
$this->getActivity()->log_name = $logName;
Expand Down
14 changes: 14 additions & 0 deletions tests/ActivityLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -323,4 +323,18 @@ public function it_can_log_activity_when_attributes_are_changed_with_tap()
$this->assertEquals('value', $firstActivity->getExtraProperty('property.subProperty'));
$this->assertEquals(Carbon::yesterday()->startOfDay()->format('Y-m-d H:i:s'), $firstActivity->created_at->format('Y-m-d H:i:s'));
}

/** @test */
public function it_will_log_a_custom_created_at_date_time()
{
$activityDateTime = now()->subDays(10);

activity()
->createdAt($activityDateTime)
->log('created');

$firstActivity = Activity::first();

$this->assertEquals($activityDateTime->toAtomString(), $firstActivity->created_at->toAtomString());
}
}