Reputation: 2505
I am trying to count number of views for my products. For that there is a column view_count
in my products table. I am trying to implement it with event listener.
This is my event code :
ProductWasViewed.php
<?php namespace App\Events;
use App\Events\Event;
use App\Modules\Product\Models\Product;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ProductWasViewed
{
use SerializesModels;
public $product;
public function __construct(Product $product)
{
$this->product = $product;
}
public function broadcastOn()
{
return [];
}
}
this is my listener code
IncrementProductViewCount.php
<?php namespace App\Listeners;
use App\Events\ProductWasViewed;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Modules\Product\Models\Product;
class IncrementProductViewCount
{
public function __construct() { }
public function handle(ProductWasViewed $event)
{
$event->product->increment('view_count');
}
}
EventServiceProvider.php
Array:
'App\Events\ProductWasViewed' => [
'App\Listeners\IncrementProductViewCount',
],
Controller where i used the event listener:
public function singleProduct(Request $request)
{
$name = $request->name;
$product = DB::table('products')
->where('name' , '=', $name)
->where('status','=',1)
->first();
Event::fire(new ProductWasViewed($product));
}
The error that I am getting:
Type error: Argument 1 passed to App\Events\ProductWasViewed::__construct() must be an instance of App\Modules\Product\Models\Product, instance of stdClass given
How do i resolve the problem? Please help.
Upvotes: 3
Views: 2163
Reputation: 163768
Query Builder request returns stdClass
object. You need to use Eloquent here to get Product
object:
$product = Product::where('name', $name)->where('status', 1)->first();
Upvotes: 2