For example, I have five tables (School, Student, Class, Session, and Enrollment) the Enrollment Table store the Primary Key of other tables, Now I like to count in Session wise that how Many students have enrolled in Session 2019-2020 and display in the dashboard.
public function index()
{
$schools=School::all();
$students=Student::all();
$sessions=Session::all();
$enrollements=Enrollement::all();
return view('dashboard',compact('schools','students','enrollements','sessions'));
}
could anyone suggest the best method to solve the following problem?
For collections , use last()
method ($sessions->last()
) https://laravel.com/docs/7.x/collections#method-last
I don't know how your table is structured, but you need to group by year and then compare
$enrollementsByYear = Enrollment::selectRaw('year, count(year) AS enrollmentsByYear')
->groupBy('year')
->get();
Then in $enrollementsByYear
you will have a collection where you can compare the year of the session and mount your table. Change year
with the actual column name.
You can easily compare with something like:
@foreach ($sessions as $session)
@foreach ($enrollementsByYear as $y)
@if ($session->year == $y->year)
<label>{{ $session->year }}</label>: <span> {{$y->enrollmentsByYear }}</span>
@endif
@endforeach
@endforeach