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 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析