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.
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
]
I think you're confusing events and listeners - you're firing off the listener to Event::fire()
and you pass the $artist
into the constructor of the listener, but instead try and take it off the $event
.
Keep in mind if your queue driver isn't sync
then you will actually need to run your queue from the command line, otherwise these jobs will never be run.
Below is an example of how you might do this with a job that you dispatch. You could fire this off by calling dispatch(new RecordArtistView($artist))
.
<?php
namespace App\Jobs;
use App\Artist;
use App\Jobs\Job;
use Illuminate\Contracts\Queue\ShouldQueue;
class RecordArtistView extends Job implements ShouldQueue
{
protected $artist;
/**
* Create a new job instance.
*
* @param \App\Artist $artist
* @return void
*/
public function __construct(Artist $artist)
{
$this->artist = $artist;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->artist->increment('week_hits');
}
}