Home > Net >  Laravel first()->count() return more than one
Laravel first()->count() return more than one

Time:02-13

I'm going to count total record of eloquent query using count().

My table looks like this

id Code Discount
1 StarterResellerFree30Days 100
2 StarterResellerFree33Days 100
3 StarterResellerFree32Days 100
4 StarterResellerFree31Days 100
5 StarterResellerFree60Days 10

Here is my code

 $eligible = Coupon::where('code', 'StarterResellerFree30Days')->first();
 echo $eligible->discount;
 echo "<br><br>";
 echo $eligible->count();

Here is the result

100

5

As you can see $eligible->discount return expected value, meaning $eligible contain only 1 record.

However, when I use $eligible->count(), it is returning 5 which is total records.

$eligible->count() supposed to return 1 because of first() and there is only one record matching the criteria.

Where am I doing wrong?

Thanks

CodePudding user response:

You made a mistake using first() method which is returning MODEL. You have to use get() method to return collection so you can do count() on collection retreived. When you use count on model it will return you number of models in database.

So you want to use

$eligable = App\Models\Coupon::where('code', 'StarterResellerFree30Days')->get();

as per on example below:

enter image description here

  • Related