php – Collection could not be converted to int Laravel-ThrowExceptions

Exception or error:

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.


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)

    return ($countOfReviews > 1 ? true : false);  //Error comes from this line


 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>

How to solve:

$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)

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.

Leave a Reply

Your email address will not be published. Required fields are marked *