简体   繁体   中英

How to count rows in database table?

I want to make a variable

{{ $countEvents }}

which can count the number of rows from table Events...Now I have 18 rows( https://imgur.com/a/zt35XwV ), I want to use this variable to my view. How can I be able to count the number of rows?

I've tried this

$events = Event::count();

but I got all data with all columns from my database, not the number of it!

Controller:

$countEvents = Event::count();

return view('view-name-here', compact('countEvents'));

this will allow you to use {{ $countEvents }} in your view

You can use DB query builder facade.

$data['countEvents'] = DB::table('events')->count();

Now in blade you can check integer value of $countEvents

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$eventCount = count($events);

If you have a Event model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$eventlist = Event::all();
$eventCount = $eventlist->count();

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