简体   繁体   中英

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

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": 'test@example.com', [...]}

to

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

// output: 123

You can use count method in laravel to count result.

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

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

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();

Change Your Code From

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

To

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM