Reputation: 434
I want a user to review(rate) a product only once, I saw this and tried but I'm getting an error Object of class Illuminate\Database\Eloquent\Collection could not be converted to int
how can I fix this so that a user will be able to review a product once.
Product.php
public function reviews()
{
return $this->hasMany(ProductReview::class);
}
public function currentUserHasSubmittedReview(){
$countOfReviews = $this->reviews()
->where('user_id', Auth::user()->id)
->where('product_id', $this->id)
->get();
return ($countOfReviews > 1 ? true : false); //Error comes from this line
}
ProductReview.php
public function product()
{
return $this->belongsTo('App\Product');
}
Blade file
@foreach($products as $product)
@if ($product->currentUserHasSubmittedReview() == false )
<a " href="#openModal-about">Write review</a>
@else
@endif
@endforeach
Upvotes: 0
Views: 1206
Reputation: 35170
$countOfReviews
is a Collection
but you're trying to treat it like an integer by using > 1
. > 1
will only return true if there is more than 1 rather than if one exists.
One way to get around this is to use exists()
instead of get()
with the query:
public function currentUserHasSubmittedReview()
{
return $this->reviews()
->where('user_id', Auth::user()->id)
->where('product_id', $this->id)
->exists();
}
The above will be more efficient as well since the database is doing more of the lifting and you're not having to load multiple collection instances just to count them after the fact.
Upvotes: 3