Perform a related table search in Laravel and page

0

I would like to search all the people of a given class based on the class code using Laravel:

And soon after page, to make a list.

Student

public function turmas()
{
    return $this->belongsToMany(Turma::class,'turma_classe', 'turma_id','aluno_id');
}

Class

public function alunos()
{
    return $this->belongsToMany(Aluno::class,'turma_classe', 'aluno_id','turma_id');
}

Search

$aluno = Aluno::find(1);
$turmas = $aluno->turmas;

foreach($turmas as $turma)
{
    var_dump(Aluno::with(Turma::class)->where('codigo', $turma->codigo));
}
    
asked by anonymous 23.01.2018 / 13:44

1 answer

1

You already have the ready relationship in models , just use the alunos navigation property in the Turma model.

$turma = Turma::where('codigo', $codigoTurma)->first();

$alunos = $turma->alunos;

To page you can use the paginate method of Laravel, it has almost everything that is necessary to make a pagination in it.

$registros = $alunos->paginate();

See more in the Laravel documentation.

    
23.01.2018 / 14:19