cyrildewit / eloquent-viewable

Associate views with Eloquent models in Laravel
MIT License
803 stars 104 forks source link

`touch` the parent timestamp if the view has been recorded #266

Closed aasutossh closed 2 years ago

aasutossh commented 2 years ago

How do I go about implementing it? Is there some event that gets fired if the view has been recorded? Or I need to have my custom Views.php and View.php?

aasutossh commented 2 years ago

I am using algolia as search service. I want to sort by the views too. For that, I need to re index the table when view gets updated. And to achieve that I need to update the timestamp if the view has been recorded.

        // record product view
        $expiresAt = now()->addHours(3);
        views($product)
            ->cooldown($expiresAt)
            ->record();
aasutossh commented 2 years ago

The record() method returns boolean.

$expiresAt = now()->addHours(3);
        if (views($product)
            ->cooldown($expiresAt)
            ->record()) {
            $product->touch();
        }

Seems to work fine.

cyrildewit commented 2 years ago

I think the way you implemented it is fine. Another option would be to create an observer for the View model and watch for the created event.