phpeloquentlaravel-bladelaravel-views

Laravel Dashboard Query on Enrolled students this Year?


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'));
    }
  1. when I write {{$sessions->latest()}} it show the following error """Method Illuminate\Database\Eloquent\Collection::latest does not exist""
  2. and how to pass session year (String) to enrollement to count?

could anyone suggest the best method to solve the following problem?


Solution

    1. For collections , use last() method ($sessions->last()) https://laravel.com/docs/7.x/collections#method-last

    2. 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