DevAdewale
DevAdewale

Reputation: 61

How to count results from database?

I want to count the result fetched from database

$t = Activation::where('user_id', '=', $user->id)->first();

$w=(count($t));
dd($w);

I expect to see the number of results fetched

Upvotes: 0

Views: 77

Answers (3)

zahid hasan emon
zahid hasan emon

Reputation: 6233

You are using first() that will return only one object if found. use get() and then use count.

$t = Activation::where('user_id',$user->id)->get();
$w = count($t);

If you just want to count then use count()

Activation::where('user_id',$user->id)->count();

Upvotes: 0

Amit Senjaliya
Amit Senjaliya

Reputation: 2945

Try to use a laravel count method.

$t = Activation::where('user_id', '=', $user->id)->count();
dd($t);

$ty = Activation::where('user_id', '=', $user->id)->count();
dd($ty);

Upvotes: 0

IlGala
IlGala

Reputation: 3419

Your code is wrong... Please read the Laravel official documentation

With first() function you're getting just the first result of the set returned from your query. To make your code work you should use the get() function. and the dd($w) will return the correct result.

Anyway there are specific aggregate functions to achieve your goal, just changing your code from

Activation::where('user_id', '=', $user->id)->first();

// output: {"user_id": 1, "email": '[email protected]', [...]}

to

Activation::where('user_id', '=', $user->id)->count();

// output: 123

Upvotes: 1

Related Questions