Ad

Laravel Increment A Polymorphic Relationship Column

I currently have a listener set up like this that fires an event whenever a page is being served from a controller:

public function handle(BarPageWasViewed $event)
{
    // increment the pageview for this particular bar whenever the event fires
    $event->bar->views()->create(['views' => 1]);
}

This inserts a polymorphic relationship and sets the corresponding views column to 1.

Now whenever this relationship already exists I just want to increment the view. How do I go about doing this? The $event i pass is simply the 'bar' model that is currently being viewed.

Ad

Answer

Figured it out, for anyone that is dealing with the same problem:

public function handle(BarPageWasViewed $event)
    {
        if(count($event->bar->views) === 0) {
            $event->bar->views()->create(['views' => 1]);
        } else {
            $event->bar->views()->increment('views');
        }
    }
Ad
source: stackoverflow.com
Ad