Search code examples
laraveleloquentlaravel-permission

Getting result only for a specified id in Eloquent


I have a little problem. My code is working, but I think I'm not doing it the proper way.

In my GradeController i have this code:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    if(auth()->user()->hasRole('Student')) {
        $subjects = Subject::all();

        return view('grades.student.index', compact('subjects'));
    }
}

And in my view I'm getting Grades which belong to a specified user this way:

@foreach($subject->grades->where('student_id', '=', auth()->user()->id) as $grade)
<span class="badge badge-primary">
    {{ $grade->value }}
</span>@endforeach

Is here, I mean Laravel, any better way to do this? Because I think that getting all Grades which belong to a Subject and then look for ID is not very "effective".

Have a good day.


Solution

  • You can use the with() eager loading helper, with a closure which will filter the subject's 'grades` based on the grade belonging to the logged in user:

    $subjects = Subject::with(['grades' => function($query) {
        $query->where('student_id', auth()->user()->id);
    }])->get();
    

    Note the removal of , '=', in the ->where() clause. It does not need this argument if checking if equal to.