Problem in a laravel view

1

How can I show the number of students per course in an index view?

These are the relationships in my models Student:

public function curso()
{
    return $this->belongsTo(Curso::class,'id_curso','id');
}

Course:

public function alumnos()
{
    return $this->hasMany('App\Alumno','id_curso');
}

Someone who helps me please I am new to this, my idea is a count of students where the course id is equal to the course in question, but for that I need the ID of the course. this is my controller

public function index(Request $request)
{
    $cursos = Curso::search($request->nombre)->orderBy('nombre','ASC')->paginate(10);
    return view('cursos.index')->with('cursos',$cursos)->with('i', ($request->input('page', 1) - 1) * 5);
}
    
asked by Edgardo Escobar 31.03.2017 в 00:54
source

1 answer

0

If you already have the established relationship, you can simply use the withCount() method to get the count of the related items:

$cursos = Curso::search($request->nombre)->withCount('alumnos')->orderBy('nombre', 'ASC')->paginate(10);

In the view, in the iterations:

{{ $curso->alumnos_count }}

More information in the documentation: link

    
answered by 31.03.2017 / 01:35
source