1

I want to make a variable

{{ $countEvents }}

which can count the number of rows from table Events...Now I have 18 rows( https://i.sstatic.net/ZUJoY.jpg ), 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!

2
  • Try finding all Events and then count() on the results then pass to the view Commented Jun 25, 2019 at 12:33
  • Could you post your Event model code? Event::count() should work without any problems and return only the count of rows, when Event::all()->count() will first receive all the rows from the table and then count the results (not the best way of doing it). Commented Jun 25, 2019 at 12:36

3 Answers 3

3

Controller:

$countEvents = Event::count();

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

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

Sign up to request clarification or add additional context in comments.

6 Comments

check this solution my man - nice and simple - you were on the right lines
you don't need to do $events::all() you can just do this above
no worries man glad you got there! - if you could please accept my answer that would be great
the countEvents worked for EventController. But can I add a countNews in EventController? I used $countNews = News::count(); but I've got undefined variable $countNews. the return is this return view('event.view_all_event',$data, compact('countEvents'), compact('countNews'));
yeah you can do that like this - Controller: $countNews = \App\News::count(); and then return view('view-name-here', compact('countEvents', 'countNews')); - let me know how you get on
|
1

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

Comments

1

You can use DB query builder facade.

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

Now in blade you can check integer value of $countEvents

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.