dougutuo9879 2017-02-26 02:10
浏览 40
已采纳

laravel 5.4使用事件和侦听器增加页面命中率

I have two models with many to many relationship artists and songs.

then there are fields in my artists table called weekhits and week_date, i want to increment the value of week-hits when ever a specific artist page is visited by the user

so made event listners

class ArtistEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $artist;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(artist $artist)
    {
        //
        $this->artist = $artist;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

ant this is the listener

class ArtistViewed
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ArtistEvent  $event
     * @return void
     */
    public function handle(ArtistEvent $event)
    {
        $event->artist->increment('week_hits');
    }
}

and here is where i fired the listener.

public function artist($id,$slug){
        $artist = Artist::where('id', $id)->where('slug', $slug)->first();
        Event::fire(new ArtistViewed($artist));

        return view('front.artist', compact('artist'));
    }

but this code isnot incrementing week-hits field in my artists table..

plz help. iam in the middle of learning laravel.

  • 写回答

2条回答 默认 最新

  • dqunzip3183 2017-02-27 03:40
    关注

    I have already added an answer that suggests using a job for this, but if you want to go with the existing event/listener setup then just fix the call to Event::fire() to actually fire your event, not your listener.

    Event::fire(new ArtistEvent($artist))
    

    Also ensure that the event and listener are registered in your EventServiceProvider's $listen array.

    \App\Events\ArtistEvent::class => [
        \App\Listeners\ArtistViewed::class
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计