-1

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.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Tomek Greber
  • 5
  • 1
  • 7
  • One idea: You can take a look at Laravel Scopes where you can move this `->where('student_id', '=', $userId)` part there just to clean up. Also I wouldn't suggest querying in the blade file, I'd say do it in your backend and pass to `return view()` part – senty Jun 26 '19 at 08:17

2 Answers2

1

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.

thisiskelvin
  • 4,136
  • 1
  • 10
  • 17
0

In your controller index() you can make a middleware instead of doing this check auth()->user()->hasRole('Student') many times, buy if you will check only once here it will be fine what you did.

public function index()
{
    // refactoring 
    return view('grades.student.index', ['subject' => Subject::all()]);
}

Also its not good to make a query in your blade file, so you can pass grades directly from you controller

public function index()
{
    return view('grades.student.index', [
        'grades' => Grade::where('student_id', auth()->id())->get()
    ]);
}

In index blade file you can now use:


@foreach($grades as $grade)
<span class="badge badge-primary">
    {{ $grade->value }}
</span>
// you can get the subject from $grade->subject
@endforeach 
Faid
  • 554
  • 1
  • 5
  • 18